Hi I am learning C# 3.5 and wanna to know that what [STAThread] do in our programs?
Thank you
Hi I am learning C# 3.5 and wanna to know that what [STAThread] do in our programs?
Thank you
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.
It tells the compiler that you're in a Single Thread Apartment model. This is an evil COM thing, it's usually used for windows forms (gui's) as that uses Win32 for it's drawing which is implemented as STA. If you using something that's STA model from multiple threads then you get corrupted objects.
This is why you have to invoke onto the Gui from another thread (if you've done any forms coding).
Basically don't worry about it, just accept that windows gui theads must be marked as STA otherwise weird stuff happens.
The STAThreadAttribute marks a thread to use the Single-Threaded COM Apartment if COM is needed. By default, .NET won't initialize COM at all. It's only when COM is needed, like when a COM object or COM Control is created or when drag 'n' drop is needed, that COM is initialized. When that happens, .NET calls the underlying CoInitializeEx function, which takes a flag indicating whether to join the thread to a multi-threaded or single-threaded apartment.
Read more info here
and