我学习C#3.5,我想知道是什么[STAThread]
确实在我们的节目?
Answer 1:
The STAThreadAttribute
is essentially a requirement for the Windows message pump to communicate with COM components. Although core Windows Forms does not use COM, many components of the OS such as system dialogs do use this technology.
MSDN explains the reason in slightly more detail:
STAThreadAttribute indicates that the COM threading model for the application is single-threaded apartment. This attribute must be present on the entry point of any application that uses Windows Forms; if it is omitted, the Windows components might not work correctly. If the attribute is not present, the application uses the multithreaded apartment model, which is not supported for Windows Forms.
This blog post (Why is STAThread required?) also explains the requirement quite well. If you want a more in-depth view as to how the threading model works at the CLR level, see this MSDN Magazine article from June 2004 (Archived, Apr. 2009).
Answer 2:
请将STAThreadAttribute标志着一个线程使用单线程COM公寓是否需要COM。 默认情况下,.NET不会在所有初始化COM。 只有当需要COM,创建或当“n”个需要拖放,该COM被初始化一个COM对象或COM控制时等。 当发生这种情况,.NET调用底层的CoInitializeEx功能,需要一个标志,指示是否加入线程多线程或单线程单元。
了解更多信息这里 (存档,2009年6月)
和
为什么STAThread要求?
Answer 3:
它告诉你在单线程单元模型是编译器。 这是一个邪恶的COM的东西,它通常用于Windows窗体(GUI的)作为使用的Win32为其绘制,这是为STA实现。 如果你正在使用的东西,是从多个线程STA模型,然后你会得到损坏的对象。
这就是为什么你必须调用到桂从另一个线程(如果你做任何的编码形式)。
基本上不用担心,只是接受了Windows GUI线程必须标记为STA否则怪异的事情发生。