C#中[STAThread]的作用

C#的关键字 [STAThread]即 single-threaded apartment
一:
每个Thread都有一个关于ApartmentState的属性,可以把它设置为:STA或者MTA,或者UNKNOWN。
当你想指定工程的启动窗口的时候,你需要在该窗口类中申明一个Main()方法,并为这个方法设置[STAThread]属性。
详细信息,清查阅MSDN中关于Threading和COM Interop和COM+ Apartment Model的文章:

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguidnf/html/cpconmanagedunmanagedthreading.asp
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguidnf/html/cpconadvancedcominterop.asp
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cossdk/htm/pgservices_synchronization_8703.asp

二:
[STAThread]是Single  Thread  Apartment单线程套间的意思,是一种线程模型,用在程序的入口方法上
(在C#和VB.NET里是Main()方法),来指定当前线程的ApartmentState 是STA。用在其他方法上不产生影响。
在aspx页面上可以使用AspCompat = "true" 来达到同样的效果。这个属性只在  Com  Interop  有用,
如果全部是  managed  code  则无用。简单的说法:[STAThread]指示应用程序的默认线程模型是单线程单元 (STA)。
启动线程模型可设置为单线程单元或多线程单元。如果未对其进行设置,则该线程不被初始化。也就是说如果你用的.NET Framework,
并且没有使用COM Interop,一般不需要这个Attribute。其它的还有MTA(多线程套间)、Free  Thread(自由线程)。
单线程套间,简单来说所有对于单线程套间中对象的访问都是通过消息来传递的,所以同一时间只有一个线程能够访问单线程套间中的对象。

三:

C#中,[STAThread]代表什么意思?如何用?
Single Thread Apartment

>Why is STAThread required?

it changes the apartment state of the current thread to be single threaded

>Single Thread Apartment vs MultiThread Apartment?

Correct: With the STAThread attribute, you will be interacting with COM processes in a
"Single Threading Apartment" model. Without it, you will be interacting with COM processes
in the "Multiple Threading Apartment" model.

> so why do I need it....or why would I want it at some point?

You may want to interact with a COM process in a MTA model for performance reasons. You may
want to interact with a COM process in a STA model because of a design requirement. For example,
to use the Windows clipboard (System.Windows.Forms.Clipboard) you must be calling from a thread
running in a STA. If the calling thread was started by your application you can set the ApartmentState
(System.Threading.ApartmentState) before starting, but if you want to use the clipboard from your a
pplication's main thread, you need to use the System.STAThread attribute on your Main method.

> why does Main( ) only function as an entry point when it is declared static?

The simple answer is that is just the way that Microsoft designed the language. One way you can look at
this though, is there should only be 1 "instance" of your Main method - the main method has nothing to do
with any specific instances of the class it is defined in, and should therefore be static. In my opinion
it might have been a good idea to give the Main method a property similar to a static contructor where it is
executed once, and only once. Anyway, because the Main method is static, you can execute your program without
having to create any arbitrary objects.

posted @ 2007-12-13 17:43  不染丹心  阅读(23310)  评论(0编辑  收藏  举报