views:

48

answers:

3

If I call the same COM function from multiple threads to an in proc COM Dll, how thread safe is that?

Do all my objects in the COM DLL also need to be thread safe for this to work reliably?

A: 

Depends upon the COM objects threading model. If its free threaded then you are responsible for thread safety. If its in a single threaded apartment then you can only call it from one, and if it's in a multithreaded apartment, then you can can but as always you have to consider the implications for the object's state. there is a very good answer on SO http://stackoverflow.com/questions/127188/could-you-explain-sta-and-mta/127240#127240 explaining this.

Preet Sangha
Can an existing COM DLL be changed from STA to MTA???
Tony
Not really. It all about design of the original code. If the code is not designed to be multithreaded, then you must marshal access - i.e. handle it your self.
Preet Sangha
I want to make it possible for my COM objects to be called concurrently. From my understanding with STA that is not possible, but if the threading model was MTA it would be possible?
Tony
@Tony: Yes, but to "convert" STA to MTA you need to carefully analyze and possibly rewrite the code.
sharptooth
+2  A: 

COM takes care of threading on behalf of the COM server. The server publishes the kind of threading it supports with the ThreadingModel registry key. Very common settings are Apartment or Both. Free is very rare. A missing key is equivalent to Apartment.

COM requires a single-threaded apartment (STA) for apartment threaded servers. If you don't provide one (CoInitialize/Ex call) then it will create a dedicated thread for the server. A hard requirement for an STA thread is that it also pumps a Windows message loop. The message loop is the mechanism by which COM automatically marshals a method call from one thread to another.

So, the general answer to your question is, yes, it normally is thread-safe. There are still things that can go wrong. Deadlock is possible when a call is made from a worker thread but the STA thread isn't pumping. Or the server could be fibbing about the ThreadingModel it registered. Not uncommon with servers implemented in .NET. They get registered as Both, but there are few .NET classes that are actually thread-safe.

Hans Passant
+1  A: 

See this very detaled article. Basically COM will take care of synchronization - you don't need to bother. However in certain cases the consumer can experience significant slowdown because of synchronization.

sharptooth