Thursday, January 21, 2016

Inter-Process Locking

Many years ago I had to share a file between apps running in different Windows processes, and I had to guarantee that only one process would update the file at any time. Now I can't find my old C# code or remember exactly how I created an inter-process lock. Web searches reveal lots of different code samples, and they're much longer and more complicated that what I remember of my old code. So after bumbling around for half an hour I finally rediscovered the simplest possible code, which I publish here so it won't be forgotten again.

Console.WriteLine("Before lock");
using (var m = new Mutex(false, "TheMutexName"))
{
  m.WaitOne();
  Console.WriteLine("Pretend work now. Press enter to continue...");
  Console.ReadLine();
  m.ReleaseMutex();
}
Console.WriteLine("After lock. Press enter to exit");
Console.ReadLine();

The code between the WaitOne and ReleaseMutex is guarded against entry by multiple threads in any processes on the machine.

No comments:

Post a Comment