I am trying to implement a memory mapped file in my application (specifically a Windows service), and then use a C # form to read from the MMF that the service writes. Unfortunately, I cannot get a form to read anything from the MMF, more importantly, the form never finds the MMF created by the Service. Below are the code snippets that describe what they are doing, can someone see what I'm doing wrong, or be able to point me in the best 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);
view.Position = 0;
view.Read(rmsg, 0, 1);
Log.Error("Finished MMF", rmsg[0].ToString());
mutex.ReleaseMutex();
}
the 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)
{
**
}
}
}
In addition, while the Run service is running, the MMF should always have a descriptor and should not be collected by the garbage collector;
source
share