This example shows how you can use a mutex in C# to perform cross-process locking. For me, I needed a way to perform file system synchronization across multiple processes. Mutexes provide locking at the OS level to allow you to block until the Mutex is obtained (or to timeout if it is not obtained).

For a full understanding of Mutexes, you should thoroughly review the C# documentation.

The code below should correctly handle mutex conditions by doing the following:

  1. creating a named mutex that can be obtained across multiple processes
  2. attempting to obtain the mutex and blocking the current thread
  3. handling AbandonedMutexException in the event the previous process fails
  4. handling an acquisition timeout
  5. correctly releasing an obtained mutex after work is performed (or an exception occurs)
// create a global mutex
using (var mutex = new Mutex(false, mutexName))
{
    Console.WriteLine("Waiting for mutex");
    var mutexAcquired = false;
    try
    {
        // acquire the mutex (or timeout after 60 seconds)
        // will return false if it timed out
        mutexAcquired = mutex.WaitOne(60000);
    }
    catch(AbandonedMutexException)
    {
        // abandoned mutexes are still acquired, we just need
        // to handle the exception and treat it as acquisition
        mutexAcquired = true;
    }

    // if it wasn't acquired, it timed out, so can handle that how ever we want
    if (!mutexAcquired)
    {
        Console.WriteLine("I have timed out acquiring the mutex and can handle that somehow");
        return;
    }
    
    // otherwise, we've acquired the mutex and should do what we need to do,
    // then ensure that we always release the mutex
    try
    {
        DoWork(path);
    }
    finally
    {
        mutex.ReleaseMutex();
    }
    
}

The example code below can be found in its runnable form on Github: https://github.com/bmancini55/csharp-mutex.

Try running multiple instances of the program at the same time and obsever its behavior!