[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+:

  1. Each STA can have only one thread.
  2. Components that use STA threads must retrieve and dispatch window messages.
  3. Always remember to marshal interface pointers between threads running in different apartments.
  4. Call CoInitializeEx from every thread that uses COM+ services in order to declare the supported threading model.
  5. Each object is associated with one and only one apartment, but an apartment can contain multiple objects.
  6. The main STA is created by the first thread to call CoInitialize or CoInitializeEx(NULL, COINIT_APARTMENTTHREADED) within a process.
  7. The main STA should remain alive until the process has completed all COM+ work with legacy components.
  8. A process can have any number of STAs but at most one MTA and one NA.
  9. Always define the ThreadingModel value in the registry for in-process objects.
  10. Build nonvisual in-process objects that support the NA model (ThreadingModel = Neutral).