Mutex in C#

Mutex in C# with Example

In this article, I am going to discuss how to use Mutex in C# in a multithread application for thread synchronization with some examples. Please read our previous article where we discussed how to use the Monitor class to protect the shared resources from concurrent access in the multithread application.

What is Mutex?

Mutex in C# also work likes a lock i.e. acquired an exclusive lock on a shared resource from concurrent access, but it works across multiple processes. As we already discussed exclusive locking is basically used to ensure that at any given point of time, only one thread can enter into the critical section.

The Mutex class provides the WaitOne() method which we need to call to lock the resource and similarly it provides ReleaseMutex() which is used to unlock the resource. Note that a Mutex can only be released from the same thread which obtained it.

Example:

The following example shows the use of Mutex class in C#. The code is self-explained. So, please go through the comment lines.

using System;
using System.Threading;

namespace MutexDemo
{
    class Program
    {   
        private static Mutex mutex = new Mutex();

        static void Main(string[] args)
        {
            //Create multiple threads to understand Mutex
            for (int i = 1; i <= 5; i++)
            {
                Thread threadObject = new Thread(MutexDemo);
                threadObject.Name = "Thread " + i;
                threadObject.Start();
            }
            Console.ReadKey();
        }

        //Method to implement syncronization using Mutex  
        static void MutexDemo()
        {
            Console.WriteLine(Thread.CurrentThread.Name + " Wants to Enter Critical Section for processing");
            try
            {
                //Blocks the current thread until the current WaitOne method receives a signal.  
                //Wait until it is safe to enter. 
                mutex.WaitOne();  
                Console.WriteLine("Success: " + Thread.CurrentThread.Name + " is Processing now");
                Thread.Sleep(2000);
                Console.WriteLine("Exit: " + Thread.CurrentThread.Name + " is Completed its task");
            }
            finally
            {
                //Call the ReleaseMutex method to unblock so that other threads
                //that are trying to gain ownership of the mutex.  
                mutex.ReleaseMutex();
            }
        }
    }
}

Output:

Mutext in C# with Example

That’s it for today. In the next article, I am going to discuss the use of Semaphore in C# with some examples. Here, in this article, I try to explain Mutex with an example. I hope you enjoy this article.

Leave a Reply

Your email address will not be published. Required fields are marked *