From the MSDN article on STAThread:
Indicates that the COM threading model for an application is single-threaded apartment (STA).
(For reference, that's the entire article.)
Single-threaded apartment... OK, that went over my head. Also, I read somewhere that unless your application uses COM interop, this attribute actually does nothing at all. So what exactly does it do, and how does it affect multithreaded applications? Should multithreaded applications (which includes anything from anyone using Timer
s to asynchronous method calls, not just threadpools and the like) use MTAThread, even if it's 'just to be safe'? What does STAThread and MTAThread actually do?
What that does it it ensures that
CoInitialize
is called specifying COINIT_APARTMENTTHREADED as the parameter. If you do not use any COM components or ActiveX controls it will have no effect on you at all. If you do then it's kind of crucial.Controls that are apartment threaded are effectively single threaded, calls made to them can only be processed in the apartment that they were created in.
Some more detail from MSDN:
Apartment threading is a COM concept; if you're not using COM, and none of the APIs you call use COM "under the covers", then you don't need to worry about apartments.
If you do need to be aware of apartments, then the details can get a little complicated; a probably-oversimplified version is that COM objects tagged as STA must be run on an STAThread, and COM objects marked MTA must be run on an MTA thread. Using these rules, COM can optimize calls between these different objects, avoiding marshaling where it isn't necessary.
STAThread is written before the Main function of a C# GUI Project. It does nothing but allows the program to create a single thread.