Communication between two plugins in C#

381 Views Asked by At

I have two plugins that are running inside a third-party host application. The host application has an event called DocumentOpened that is raised when a document is opened.

Both plugins, Plugin A and Plugin B, are subscribing to this event. However, Plugin A and Plugin B do not know about each other, and they are executed independently.

Plugin A)

Host.DocumentOpened += SomeCodeA()


Plugin B)
Host.DocumentOpened += SomeCodeB()

What I want to achieve is to give control back to Plugin A after Plugin B has finished handling the DocumentOpened event. In other words, I want to call a method in Plugin A after Plugin B has finished executing.

1

There are 1 best solutions below

0
JonasH On

To do this to do this you will probably need some way for Plugin A and B to communicate with each other. Here are some methods, but there is probably others:

EventWaitHandle

One fairly simple way would be with a system wide synchronization event. Both plugins would each create a EventWaitHandle with the same name. Plugin A could then create a thread that waits on the event, and Plugin B would set the event. If Plugin B does not exist then the event would never be raised. This is a system wide event, so would not work if multiple instances of the host is running, unless you do something like including the processor-id to the event name.

IPC/RPC methods

There are various ways for processes to communicate with each other that could be used:

  • Named pipes
  • Message buss
  • web service
  • Windows communication foundation

This would be a more complicated solution, but would also be more generic. It could for example handle if the host application decides to run plugins in separate processes, or if you want to transfer more data between the plugins.

Shared assembly

You could create an assembly that is used by both of your plugins. This would allow you to create a singleton object that is shared between both plugins. Something like this:

public class PluginCommunication
{
    public event EventHandler MyEvent;
    public void RaiseEvent() => MyEvent?.Invoke(this, EventArgs.Empty);
    public static PluginCommunication PluginBEvent = new PluginCommunication();
}

plugin B would call PluginCommunication.PluginBEvent.RaiseEvent(); and plugin A would attach an event handler like PluginCommunication.PluginBEvent.MyEvent += PluginAEventHandler;

There are potential pitfalls with this method. if you need to change the assembly in any way you face the risk of plugin A using version 1 and plugin B using version 2, and that may end badly if you are not very careful. Threading issues might also occur if you do not do everything on the main thread.