Using C# Mutexes for interprocess synchronization

Mutexes are used in multithreaded (multiprocess) environment for organizing a mutually exclusive access to some shared resource. While usually not required for simple applications, these syncronization primitives are crucial once you advance to mutli-threaded world. Consider you have some resource, which can only be accessed from a single process or thread for consistency. Say, you have a connection to some remote server that can process only one operation at a time. Multiple requests are dropped. But you need to write two programs that do some data processing and query the server periodically. Of course, you can run them in chain one after another. Run first program, wait until it finishes, then run second program. But what if you want your programs to do background work simultaneously and only block on server requests? This will be much more effective considering you have enough CPU power at your server. There are many other similar examples like sharing the same serial port when communicating with some peripheral, etc. 

In this example we will discuss how to create and correctly use a named mutex object.

The benefit of named mutexes is that they can be shared between processes. On the contrary, unnamed mutexes can only be used within the boundaries of the same process. 

 

public static class MutexHelper
{
    private static Mutex m_mutex = new Mutex(false, "Global\\MyUniqueMutexName");

    public static void MutexTake()
    {
        try
        {
            m_mutex.WaitOne();
        }
        catch (AbandonedMutexException)
        {

        }
    }
    
    public static void MutexLeave()
    {
        m_mutex.ReleaseMutex();
    }
}



Usage: 

try
{
    MutexHelper.MutexTake();
    /* call your service communication code here */
    response = Service.call(...);
}
catch (Exception ex)
{
    Console.WriteLine("ex {0}", ex.Message);
}
finally
{
    MutexHelper.MutexLeave();
}

Add comment

Security code
Refresh