c# force call to out of process COM server from MTA thread to call back into same thread

444 Views Asked by At

I am writing a DLL that is called by a third party application. The DLL is called from an MTA thread and any calls back to the third party application must be done on the same thread. From my application I need to call to an out of process COM server and I would like to call back to the third party application from this COM server using an object passed to the COM server.

e.g.

// Called from third party MTA thread
// apiObject must always be called from same thread that called EntryPoint
void EntryPoint(API apiObject)
{
   IMyComClass myComObj = createComObject();
   myComObj.doStuff(apiObject);
}

Class MyComClass : IMyComClass
{
   public void doStuff(API apiObject)
   {
      apiObject.doSomething();
   }
}

Now, if I could change the thread to STA it would work just fine, but unfortunately this is out of my control.

Is there anything simple I can do to force the call coming back in from the COM server to be on the same thread?

Note that the calling application is not a windows forms or WPF application, its a windowless service.

The only thing I can think of is to create a new worker thread from which I do my calls to the COM server and implement my own event queue and just loop waiting for API calls inside EntryPoint. Then I can put delegates to the API calls onto the event queue from the worker thread ensuring they are all called from the correct thread when processing the queue in EntryPoint.

This seems like a very ugly and complex solution to something that should be quite common... Is there a simple(r) solution?

0

There are 0 best solutions below