[ACCEPTED]-STAThread and multithreading-sta

Accepted answer
Score: 63

Apartment threading is a COM concept; if 11 you're not using COM, and none of the APIs 10 you call use COM "under the covers", then 9 you don't need to worry about apartments.

If 8 you do need to be aware of apartments, then 7 the details can get a little complicated; a probably-oversimplified 6 version is that COM objects tagged as STA 5 must be run on an STAThread, and COM objects 4 marked MTA must be run on an MTA thread. Using 3 these rules, COM can optimize calls between 2 these different objects, avoiding marshaling 1 where it isn't necessary.

Score: 3

What that does it it ensures that CoInitialize is called 29 specifying COINIT_APARTMENTTHREADED as the 28 parameter. If you do not use any COM components 27 or ActiveX controls it will have no effect 26 on you at all. If you do then it's kind 25 of crucial.

Controls that are apartment threaded 24 are effectively single threaded, calls made 23 to them can only be processed in the apartment 22 that they were created in.

Some more detail 21 from MSDN:

Objects created in a single-threaded apartment 20 (STA) receive method calls only from their 19 apartment's thread, so calls are serialized 18 and arrive only at message-queue boundaries 17 (when the Win32 function PeekMessage or SendMessage 16 is called).

Objects created on a COM thread 15 in a multithread apartment (MTA) must 14 be able to receive method calls from other 13 threads at any time. You would typically 12 implement some form of concurrency control 11 in a multithreaded object's code using 10 Win32 synchronization primitives such 9 as critical sections, semaphores, or mutexes 8 to help protect the object's data.

When 7 an object that is configured to run in 6 the neutral threaded apartment (NTA) is 5 called by a thread that is in either an 4 STA or the MTA, that thread transfers 3 to the NTA. If this thread subsequently 2 calls CoInitializeEx, the call fails and 1 returns RPC_E_CHANGED_MODE.

More Related questions