Reputation: 93
I understand the reason behind STA, but don't really see the reason for MTA.
A COM object can be loaded without any apartments, right? That means it's already able to take calls asynchronously, since no one puts any constraints.
Where am I wrong?
Upvotes: 1
Views: 181
Reputation: 104
First, your assumption is wrong: a COM object can not be created outside of any apartment. Generally a thread should only create COM objects if it has previously called CoInitialize or CoInitializeEx, which places it in an apartment. Otherwise, creation will usually fail. There is the edge case of the implicit multithreaded apartment (if another thread of the same process initialized it), but even then you would be in the MTA, just in an unreliable and hard to debug way. No COM object ever exists without being in an apartment.
The reason you want an MTA is that it is not necessarily the only apartment. A process can have one MTA and arbitrarily many STAs. Calls between the MTA and any of the STAs still need to be marshaled; if they weren't, one of the MTA threads could call an STA thread in an unsafe way.
In fact having at least one STA is the rule rather than the exception: The user interface wants to live in an STA, because it depends on messages (for example because of mouse clicks etc.) to be processed in sequence.
Upvotes: 1