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. As part of this article, we are going to discuss the following pointers.

  1. What is Mutex in C#?
  2. How to use Mutex in a multithread application to protect the shared resources?
  3. Example to understand Mutex in C#.
What is Mutex in C#?

Mutex also works 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.


The following example shows the use of the C# Mutex class. 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;

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


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 *