Could you explain STA and MTA?

John picture John · Sep 24, 2008 · Viewed 140.6k times · Source

Can you explain STA and MTA in your own words?

Also, what are apartment threads and do they pertain only to COM? If so, why?

Answer

Joseph Daigle picture Joseph Daigle · Sep 24, 2008

The COM threading model is called an "apartment" model, where the execution context of initialized COM objects is associated with either a single thread (Single Thread Apartment) or many threads (Multi Thread Apartment). In this model, a COM object, once initialized in an apartment, is part of that apartment for the duration of its runtime.

The STA model is used for COM objects that are not thread safe. That means they do not handle their own synchronization. A common use of this is a UI component. So if another thread needs to interact with the object (such as pushing a button in a form) then the message is marshalled onto the STA thread. The windows forms message pumping system is an example of this.

If the COM object can handle its own synchronization then the MTA model can be used where multiple threads are allowed to interact with the object without marshalled calls.