Using Mutex to avoid deadlocks

Mutex is not new to the .NET framework. The Win32 api supports an object called Mutex and .NET framework class Mutex is actually a wrapper class for the same Win32 kernel mutex object. Mutex objects are generally used to synchronize Threads across process. Mutexes are namable and hence you can signal whether the Mutex is acquired or not by some other thread in probably some different process. You should note a Mutex is created with the call of Win32 CreateMutex call. You can check ownership of the Mutex using WaitAll, WaitAny etc calls and which avoids deadlocks.

As I have already told you, Mutex has an underlying Win32 kernel object associated with it, even though it supports cross process thread synchronization, yet it is heavier than Monitor and you need to explicitly close the mutex when it is released.

Lets us use Mutex in code to clear how you could use Mutex.

static Mutex _mlock = new Mutex();
public static long Sum()
{
    long counter = 0;
    if (_mlock.WaitOne(1000))
    {
        try
        {
            for (int i = 0; i < Repository.Count; i++)
                Interlocked.Add(ref counter, Repository&#91;i&#93;);
        }
        finally
        {
            _mlock.ReleaseMutex();
        }
    }
    return counter;
}

public static void AddToRepository(int nos)
{
    if (_mlock.WaitOne(2000))
    {

        try
        {
            for (int i = 0; i < nos; i++)
                Repository.Add(i);
        }
        catch { }
        finally
        {
            _mlock.ReleaseMutex();
        }
    }
}
&#91;/code&#93;

In this code, I have created a <code>Mutex</code> and a lock is acquired using the WaitOne  method of <code>Mutex </code>object. We have also specified the Timeout value for the Mutex.  If the Timeout is elapsed, the Mutex returns false.

If you have more than one Mutex needs to be acquired before running a code, you can put all the Mutexes in an array and call WaitHandle.WaitAll to acquire all Mutexes at a time. 

[code]
Mutex[] mutexes = { this._mlock, this._mlock2, this._mlock3};
if(WaitHandle.WaitAll(mutexes))
{
      // All mutexex acquired.
}

The WaitHandle method actually avoids the deadlock internally.
Similar to WaitAll the WaitHandle class also supports methods like WaitAny or SignalAndWait methods to acquire locks.

Use Mutex for Instance Count?

As I have already told you, Mutexes can be named and can be accessed across process, you can use Mutex to count the number of instances of a certain Thread is created in a particular machine. Lets see how to do this :

bool instanceCountOne = false;
Mutex mutex = new Mutex(true, "MyMutex", out instanceCountOne);
 using (mutex)
 {
      if (instanceCountOne)
      {
            // When there is only one Instance
       }
  }

Here we name the Mutex as MyMutex which will count all the existing processes of the System and see whether the MyMutex is newly created or its already there. The instanceCountOne identifies whether the name is newly created or not. Thus it will identify the instance count of the Mutex.

If you write this code at the Entry point of your application, you can look at how many instance of the application actually exists in the system.

I hope this post helps you.

Thank you for reading.

Abhishek Sur

Abhishek Sur is a Microsoft MVP since year 2011. He is an architect in the .NET platform. He has profound theoretical insight and years of hands on experience in different .NET products and languages. He leads the Microsoft User Group in Kolkata named KolkataGeeks, and regularly organizes events and seminars in various places for spreading .NET awareness. He is associated with the Microsoft Insider list on WPF and C#, and is in constant touch with product group teams. He blogs at http://www.abhisheksur.com His Book : Visual Studio 2012 and .NET 4.5 Expert Development Cookbook. Follow Abhishek at Twitter : @abhi2434