Sharing a memory map simultaneously between processes

浪子不回头ぞ 提交于 2021-01-28 01:07:27

问题


After overcoming some other difficulties, I'm now stuck with this (probably simple) problem.

My goal:

  • Multiple instances of my application are running and performing operations (read & write) on the same file at the same time
  • Solution (what I want to do): use memory-mapped files to speed up the execution. When the app starts, it attempts to call CreateFromFile( ) (I understand that if the file has already been mapped by someone else, this will do nothing but return the "handle"), then proceeds to perform its work on the file.

The problem is that I'm getting an IOException (The file is being used by another process) upon an attempt to CreateFromFile( ) when another process has already done so and not disposed of MemoryMappedFile object. I could, theoretically, use mutexes and constantly dispose of the objects using the using statement, but that dumps the contents to disk, slowing the execution down again and defeating the purpose.

What are the possible solutions to my problem?

I could, theoretically, CreateOrOpen( ) a non-persisted file, then dump it to disk when needed, but I believe there's a better approach?

EDIT : I feel I didn't make myself clear. All instances of the app need to work on the file constantly, they open it and use it for the next 10, 20, 60 minutes without closing the file. Eventually all of them will be killed and that's when the OS steps in, flushing the map file to disk.

Example programs:

Program A)

static void Main(string[] args)
    {
        var mmf = MemoryMappedFile.CreateFromFile(@"C:\Users\admin\Documents\Visual Studio 2010\Projects\serialize\serialize\bin\Debug\File.dat", FileMode.Open, "name");
        var accessor = mmf.CreateViewAccessor();
        accessor.Write(5, 'd');
        Console.Read();
    }

Program B)

static void Main(string[] args)

{
    var mmf = MemoryMappedFile.CreateFromFile(@"C:\Users\admin\Documents\Visual Studio 2010\Projects\serialize\serialize\bin\Debug\File.dat", FileMode.Open, "name");
    var accessor = mmf.CreateViewAccessor();
    accessor.Write(2, 'x');
    Console.Read();
}

I run both at the same time, let them hang waiting for the Console.Read(). Ideally, they should be able to access the file at the same time (i.e. both of them could open it after the other one has), but as stated above, I'm getting an IOException.

来源:https://stackoverflow.com/questions/25074011/sharing-a-memory-map-simultaneously-between-processes

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