title: How to have processes (not threads) in C# synchronize file system access
body: <p>Earlier today I was debugging something that went a bit like this:</p>
  
  <pre><code>class Foo {
  
      void AccessCriticalSection() {
          try {
              if (IO.File.Exists("\\path\to\lock.txt")
                  throw new Exception();
              System.IO.File.Create("\\path\to\lock.txt");
              criticalSection();          
          } catch (Exception ex) {
              // ignored
          } 
      }
  
      void CriticalSection() {
          // banana banana banana
          System.IO.File.Delete("\\path\to\lock.txt");
      }
  
  }
  </code></pre>
  
  <p>Let's not even get into how terrible this is… but it's essentially trying to use a file called <code>lock.txt</code> as its mutex. The operation isn't atomic, other processes are just not getting through the critical section if another process is using it (they're intended to be able to continue after the lock is released if you can believe it), etc. etc. Obviously it needs to be fixed.</p>
  
  <p>How do I properly obtain a lock to synchronize access to the filesystem across multiple processes? The processes are multiple instances of the same process, so they can share some protocol rather than specifically locking the directory (i.e., they can easily use what is the equivalent to all instances of some class locking on something like <code>private final static Object lock = new Object();</code> to synchronize access to static methods)</p>