OK, I suspect I'm going to have difficulty even putting this in words since my understanding of COM and apartments isn't really up to the job ;-)
I have a COM in-process server/component (C++) that wraps some legacy code. Due to the limitations of this legacy code I need to ensure that the methods of the COM component are:
- only called on a single thread.
- this is always the same thread for all instances of the server.
- (which I only realised later) no re-entrant calls.
The first two I achieved by registering the server with ThreadingModel="".
The 3rd is a problem I was suprised to even encounter.
The server is being used by a multi-threaded client which I have no control over. It is creating multiple instances of the server/component on different threads and calling their DoSomething() method.
This is leading to a selection of hanging and crashing behaviour and I have seen stack traces containing two calls to DoSomething() both on the main-STA thread, but for different instances of the server.
I initially didn't even think this was possible, but I now have a partial understanding and I need to know if/how it can be prevented.
My reading suggests that I may need to use IMessageFilter in some fashion, but I'm not sure if this is something that can be done on the server side, or needs to be done by the client.
Can anybody help?
Please note I am looking to see if there are any answers at the COM level, rather than looking for suggestions about changing the way that the server code interacts with the legacy code (e.g. by running the legacy code in its own thread and implementing my own (non-COM) marshalling of the calls from all instances of the server onto that thread).