【转】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.
總結
以上是生活随笔為你收集整理的【转】C#中[STAThread]的作用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【转】RabbitMQ六种队列模式-3.
- 下一篇: 短债基金和定期哪个好?从风险和收益两方面