3

Suppose I need to convert an STA COM object into an MTA object. Single threaded apartments guarantee not just that only one thread will call the object at a time, but that it's always the same thread (thread affinity).

I think I understand the first requirement: the object and its shared data needs to be read and written in a thread safe manner.

I am less clear on what I need to ensure that my object does not require thread affinity. I am aware of two concerns:

  1. Thread local storage
  2. Locks

Are there any other common (or uncommon) issues that would cause an object to fail without an outside guarantee of thread affinity?

1 Answers1

3

The STA COM objects were guaranteed to be thread safe by the COM subsystem itself. If used correctly by the client, the COM object doesn't have to be concerned about its own thread safety.

The MTA apartment turned that on its head. The COM object now has to deal with its own thread safety entirely. The COM subsystem makes no promises about the thread access on the object, it could be from multiple threads and concurrently.

Issues to be aware of include all the thread safety issues moving a class from being thread unsafe to thread safe.

When choosing to change the apartment supported by the object, it is generally a good idea to first analyse how it is used.

  • If it is only (or generally) used in an STA, the there is no need to change it and no real benefit.
  • If the object is generally used by many other MTA objects, then changing it may be a good idea.
  • If the object is marshaled between many STA apartments, then again consider the MTA support, but only if there is a measurable improvement in performance.
Niall
  • 1,831
  • 1
  • 18
  • 20