6

我正在尝试在我的应用程序(特别是 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 应该始终有一个句柄并且不应该被垃圾收集器收集;

4

1 回答 1

14

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

您必须Global\在 mmf 名称前添加才能在全局命名空间中创建和访问对象。

所以在服务中:

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

并采用以下形式:

mmf = MemoryMappedFile.OpenExisting(@"Global\AuditStream");
于 2012-07-18T18:26:56.830 回答