C#MemoryMappedFile改变了事件

时间:2017-08-02 11:14:59

标签: c#

如何通知侦听器已通过CreateNew()创建的MemoryMappedFile已更改?我在光盘上没有物理上的MemoryMappedFile。当第一个进程更改MMF时,我希望第二个进程从MMF开始读取。与FileSystemWatcher.Changed事件类似。

MemoryMappedFile mmf = MemoryMappedFile.CreateNew("testmap", 10000);
// Second process has been started and waiting for data in MMF                                          
// Writing could be performed multiple times
using (MemoryMappedViewStream stream = mmf.CreateViewStream())
{
     BinaryWriter writer = new BinaryWriter(stream);
     writer.Write("hello world!");
}

第二个流程代码:

// The code below should executes when writing to "testmap" file was finished. 
using (MemoryMappedFile mmf = MemoryMappedFile.OpenExisting("testmap"))
{
     using (MemoryMappedViewStream stream = mmf.CreateViewStream())
     {
          BinaryReader reader = new BinaryReader(stream);
          Console.WriteLine("Process A says: {0}", reader.ReadString());
     }               
}

更新。解决方案是使用Piotr建议的Named Pipes MSDN

1 个答案:

答案 0 :(得分:0)

我建议使用Observer设计模式。像这样:

    void Main()
    {
        Observable observable = new Observable();
        Observer observer = new Observer();
        observable.SomethingHappened += observer.HandleEvent;

        observable.SaveMemoryMappedFile();
    }

    class Observable
    {
        public event EventHandler SomethingHappened;

        public void SaveMemoryMappedFile()
        {
            MemoryMappedFile mmf = MemoryMappedFile.CreateNew("testmap", 10000);
            // Second process has been started and waiting for data in MMF                                          
            // Writing could be performed multiple times
            using (MemoryMappedViewStream stream = mmf.CreateViewStream())
            {
                BinaryWriter writer = new BinaryWriter(stream);
                writer.Write("hello world!");
            }
        }
    }

    class Observer
    {
        public void HandleEvent(object sender, EventArgs args)
        {
            // The code below should executes when writing to "testmap" file was finished. 
            using (MemoryMappedFile mmf = MemoryMappedFile.OpenExisting("testmap"))
            {
                using (MemoryMappedViewStream stream = mmf.CreateViewStream())
                {
                    BinaryReader reader = new BinaryReader(stream);
                    Console.WriteLine("Process A says: {0}", reader.ReadString());
                }
            }
        }
    }

当然,必须根据您的需要进行更改。