I am trying to implement a Memory Mapped File within my application (specifically a Windows Service), and then use a C# form to read from MMF the service writes to. Unfortunately i cannot seem to get the form to read anything from the MMF, more importantly it seems that the form never finds the MMF created by the Service. Below are code snippets that outline what im doing, can anyone see what I am doing wrong or be able to point me in a better direction?
Service :
private MemoryMappedFile mmf = MemoryMappedFile.CreateOrOpen("AuditStream", 1024 * 1024);
private Mutex mutex = new Mutex(false, "MyMutex");
byte[] msg = new byte[1];
var view = mmf.CreateViewStream(0, 1);
byte[] rmsg = new byte[1];
for (int i = 0; i < 400; i++)
{
mutex.WaitOne();
for (int j = 0; j < msg.Length; j++)
{
msg[j] = (byte)i;
}
view.Position = 0;
view.Write(msg, 0, bufferSize);
//the next 3 lines verify that i wrote to the mmf and can potentially read from it
//These are just for testing
view.Position = 0;
view.Read(rmsg, 0, 1);
Log.Error("Finished MMF", rmsg[0].ToString());
mutex.ReleaseMutex();
}
Form:
private MemoryMappedFile mmf;
private Mutex mutex;
Thread t = new Thread(MmfMonitor);
t.Start();
private void MmfMonitor()
{
byte[] message = new byte[1];
while(!quit)
{
try
{
**mmf = MemoryMappedFile.OpenExisting("AuditStream");**
mutex = Mutex.OpenExisting("MyMutex");
var view = mmf.CreateViewStream(0, 1);
mutex.WaitOne();
view.Position = 0;
view.Read(message, 0, 1);
Invoke(new UpdateLabelCallback(UpdateLabel), message[0].ToString());
mutex.ReleaseMutex();
}catch(FileNotFoundException)
{
**//The AuditStream MMF is never found, and therefore doesnt every see the proper values**
}
}
}
Additionally, while the service is 'Running', the MMF should always have a handle and shouldnt get collected by the garbage collector;
The service runs in a different session, the famous "session 0". Windows objects live in a namespace that's associated with the session of the process, so your form can't see the object created in the session used by the service.
You must prepend
Global\
to the mmf name to create and access the object in the global namespace.So in the service:
and in the form: