title: Sharing a memory map simultaneously between processes
body: <p>After overcoming some other difficulties, I'm now stuck with this (probably simple) problem.</p>
  
  <p>My goal:</p>
  
  <ul>
  <li>Multiple instances of my application are running and performing
  operations (read &amp; write) on the same file <strong>at the same time</strong></li>
  <li>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.</li>
  </ul>
  
  <p>The problem is that I'm getting an IOException (<code>The file is being used by another process</code>) upon an attempt to CreateFromFile( ) when another process has already done so and not disposed of <code>MemoryMappedFile</code> object. I could, theoretically, use mutexes and constantly dispose of the objects using the <code>using</code> statement, but that dumps the contents to disk, slowing the execution down again and defeating the purpose.</p>
  
  <p>What are the possible solutions to my problem?</p>
  
  <p>I could, theoretically, CreateOrOpen( ) a non-persisted file, then dump it to disk when needed, but I believe there's a better approach?</p>
  
  <p><strong>EDIT :</strong> 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.</p>
  
  <p>Example programs:</p>
  
  <p>Program A)</p>
  
  <pre><code>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();
      }
  </code></pre>
  
  <p>Program B)</p>
  
  <pre><code>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();
  }
  </code></pre>
  
  <p>I run both at the same time, let them hang waiting for the <code>Console.Read()</code>. 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.</p>