Trouble reading from Memory Mapped File

时光怂恿深爱的人放手 提交于 2019-12-07 02:37:52

问题


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;


回答1:


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:

mmf = MemoryMappedFile.CreateOrOpen(@"Global\AuditStream", ...)

and in the form:

mmf = MemoryMappedFile.OpenExisting(@"Global\AuditStream");


来源:https://stackoverflow.com/questions/11547583/trouble-reading-from-memory-mapped-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!