COM Threading Models
COM Threading Models / Apartment Model
Definition: Multithreading in COM is referred to as the apartment model in COM
Apartment
The COM apartment is a conceptual entity that allows us to think about components and their clients in a logical way
-
An apartment is not a thread, but a thread belongs to only one apartment.
-
An apartment is not an instance of a COM object, but each COM instance belongs to only one apartment.
-
A process can have one or more apartments, depending on its implementation.
-
Apartments are created or entered by calling the CoInitialize or CoInitializeEx function. Each thread that calls CoInitialize(0) or CoInitializeEx( 0, COINIT_APARTMENTTHREADED )
- STA (Single Threaded Apartment) : Only One thread can join this Apartment.
- MTA (MultiThreaded Apartment): Multiple threads can join this Apartment.
Differences between STA and MTA
No | Feature | STA | MTA |
1 | Synchronization provided by COM | YES | NO |
2 | Uses Windows message queues | YES | NO |
3 | Can have multiple threads in an apartment | NO | YES |
4 | Must marshal interface pointers between the threads in the same apartment | N/A | YES |
5 | Must marshal interface pointers between apartments | YES | YES |
6 | Must call Coinitialize() in every thread that uses a COM Service | YES | YES |
7 | Perfomance | Slow | Fast |
NOTE: ATL object wizard allows you to set the threading model. The values can be
Threading Model | Description |
Single / No Value | Object knows nothing about threads |
Apartment | STA |
Free | MTA |
Both | Both STA & MTA |