从内存映射文件中读取问题

时间:2012-07-18 18:03:48

标签: c# ipc shared-memory

我正在尝试在我的应用程序(特别是Windows服务)中实现内存映射文件,然后使用C#表单从服务写入的MMF中读取。不幸的是,我似乎无法从MMF中读取任何内容,更重要的是,表单似乎永远不会找到服务创建的MMF。下面是代码片段,概述了我在做什么,任何人都可以看到我做错了什么或能够指出我更好的方向?

服务:

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();
 }

形式:

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**
            }
        }
    }

此外,虽然服务是“正在运行”,但MMF应该总是有一个句柄,不应该被垃圾收集器收集;

1 个答案:

答案 0 :(得分:14)

该服务在不同的会话中运行,着名的“会话0”。 Windows对象存在于与进程会话关联的命名空间中,因此您的表单无法看到在服务使用的会话中创建的对象。

您必须将Global\添加到mmf名称以创建和访问全局命名空间中的对象。

所以在服务中:

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

,格式为:

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