[Previous] [Contents] [Next]
The Ten Threading Commandments
As you've seen, apartments are a far-reaching and important
concept in COM+. Understanding how apartments work and how code running
in different apartments interacts is important for every component
developer. With single-threaded and multithreaded apartments, COM+
offers the best of both worlds: the performance and scalability of the
multithreaded apartment, which has no extra overhead for thread
switching or synchronization, and the ease of use of the
single-threaded apartment, which guarantees that the state of your
object will not be trampled by another thread. The following threading
rules will keep you safe as you travel through the land of COM+:
- Each STA can have only one thread.
- Components that use STA threads must retrieve and dispatch
window messages.
- Always remember to marshal interface pointers between threads
running in different apartments.
- Call CoInitializeEx from every thread that uses COM+
services in order to declare the supported threading model.
- Each object is associated with one and only one apartment, but
an apartment can contain multiple objects.
- The main STA is created by the first thread to call
CoInitialize or CoInitializeEx(NULL,
COINIT_APARTMENTTHREADED) within a process.
- The main STA should remain alive until the process has completed
all COM+ work with legacy components.
- A process can have any number of STAs but at most one MTA and
one NA.
- Always define the ThreadingModel value in the registry
for in-process objects.
- Build nonvisual in-process objects that support the NA model
(ThreadingModel = Neutral).