The problem?
How can application A, handle events sent by an application B, and how to implements those events in B? Knowing that B has no idea of the existence of A.
The MemoryMapped way
The following example shows how it would work, with the restriction that both applications are using the same memory space. In real code, the producer()
method would be in a different application from the consumer()
method, but this serves to illustrate an implementation:
using System;
using System.IO;
using System.IO.MemoryMappedFiles;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
void run()
{
Task.Run(() => consumer());
Task.Run(() => producer());
Console.WriteLine("Press <ENTER> to stop.");
Console.ReadLine();
}
static void producer()
{
using (var mmf = MemoryMappedFile.CreateOrOpen("MyMapName", 1024))
using (var view = mmf.CreateViewStream())
{
var writer = new BinaryWriter(view);
var signal = new EventWaitHandle(false, EventResetMode.AutoReset, "MyEventName");
var mutex = new Mutex(false, "MyMutex");
for (int i = 0; i < 100; ++i)
{
string message = "Message #" + i;
mutex.WaitOne();
writer.BaseStream.Position = 0;
writer.Write(message);
signal.Set();
mutex.ReleaseMutex();
Thread.Sleep(1000);
}
}
}
static void consumer()
{
using (var mmf = MemoryMappedFile.CreateOrOpen("MyMapName", 1024))
using (var view = mmf.CreateViewStream())
{
var reader = new BinaryReader(view);
var signal = new EventWaitHandle(false, EventResetMode.AutoReset, "MyEventName");
var mutex = new Mutex(false, "MyMutex");
while (true)
{
signal.WaitOne();
mutex.WaitOne();
reader.BaseStream.Position = 0;
var message = reader.ReadString();
Console.WriteLine("Received message: " + message);
mutex.ReleaseMutex();
}
}
}
static void Main()
{
new Program().run();
}
}
}
IMPORTANT: This implementation does not use a queue, so it is possible for the consumer to miss messages if it does not process them before a new message arrives.
If you do not want to miss any messages, you would have to use some queuing implementation instead, for example, MSMQ.