Windows message pumb / Dispatcher / RealProxy

Not so long ago I had to integrate a COM component into an application. The catch was the application had no Windows message pumb and the COM component uses exactly this message pumb for some communications.

So I need to create a thread with its own message pumb and then dispatch the calls to the component to the thread holding this message pumb.

Creating a thread is simple and quickly done.
_thread = new Thread(RunThread)
{
  Name = nameof(MessagePumpDispatcher),
  IsBackground = true
}
_thread.SetApartmentState(ApartmentState.STA);
_thread.Start();
And to start a new message pumb I can use the Dispatcher type.
_dispatcher = Dispatcher.CurrentDispatcher;

try
{
  Dispatcher.Run();
}
catch (ThreadAbortException)
{
  Thread.ResetAbort();
}
Dispatching work to this thread can be achieved by using the Invoke method on the Dispatcher.
_dispatcher.Invoke(action);
This is the whole class.


Now to send all calls of the component to the correct class I could either wrap every method and property call with dispatcher.Invoke or I can use the RealProxy type to wrap all calls in one place.

Now I can use the MessagePumpProxy with my COM wrapper like the following.
var com = MessagePumpProxy<IComponentWrapper>.Create(new ComponentWrapper());
com.DoSomething();
The ComponentWrapper type is just a small wrapper for the COM component.
public interface IComponentWrapper
{
  void DoSomething();
}

public class ComponentWrapper : MarshalByRefObject, IComponentWrapper
{
  public void DoSomething()
  {
    // call com component
  }
}
For more information about the RealProxy type you can read this blog post.

Comments

Popular posts from this blog

Components of Tasks & Threading in .NET

Creating a cordova plugin and using it with ionic

Debugging information and visual studio