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]指示應用程式的預設執行緒模式是單一執行緒 Apartment (STA)。
啟動執行緒模式可設定為單一執行緒 Apartment或多執行緒 Apartment。如果未對其進行設定,則該線程不被初始化。也就是說如果你用的.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.