Search code examples
windowscominteropcom+

Why does COM+ ignore the apartment threading model?


I have an STA COM component which is put into a COM+ application. The client creates several instances of the class in that component and calls their methods in parallel. The class is registered properly - the "ThreadingModel" for the corresponding class id is "Apartment".

I see several calls of the same method of the same class being executed in parallel inside the component - in actual component code. They are executed in the same process but in different threads.

What's happening? Is COM+ ignoring the threading model? Shouldn't STA model only allow one call at a time to be executed?


Solution

  • To avoid confusion, I won't use the term "object" in this answer. Instead let's use "class" and "instance". I'm confident we all understand the difference between them.

    Marking your COM class with a ThreadingModel of "Apartment" means that instances of it will be loaded into an STA. The process creating those instances will determine whether they all go into the same STA, or into separate STAs.

    As you've discovered, COM+ has loaded several instances into separate STAs.

    The guarantee you get with an STA is that a single instance will never be accessed by multiple threads at the same time. Separate instances of the same class, if they are loaded into separate STAs, could certainly be accessed by different threads at the same time.

    So the STA is really a way of protecting your instance data. Not your class data. Any "shared" or "static" data in your COM code will have to be protected by you.