Mutex Class in C#

Mutex Class in C# with Example

In this article, I am going to discuss Mutex Class in C# i.e. How to use Mutex in C# to Protect Shared Resources in Multithreading with Examples. Please read our previous article where we discussed How to Protect Shared Resources in Multithreading using Monitor Class in C# with Examples.

Why Mutex as we already have Lock and Monitor for Thread Safety?

Mutex also helps us to ensure that our code is thread-safe. That means when we run our code in a multi-threaded environment then we don’t end up with inconsistent results. The Locks and Monitors ensure thread safety for threads that are InProcess i.e. the threads that are generated by the application itself i.e. Internal Threads. But if the threads are coming from OutProcess i.e. from external applications then Locks and Monitors have no control over them. Whereas Mutex ensures thread safety for threads that are Out-Process i.e. the threads that are generated by the external applications i.e. External Threads.

Mutex Class in C#

Let us first understand what is External Process Or External Threads and then we will understand Mutex in C#. Let us first create a console application and then copy and paste the below code into it.

using System;
namespace MutexDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Application Is Running.......");
            Console.ReadKey();
        }
    }
}

Now, build the project and go to the project’s bin\Debug directory and there you will find the application exe file as shown in the below image.

External Threads in C#

When you double click on the Application EXE file and an external thread will execute the application code. And now if you double click multiple times, then each time a new external thread will be created and execute our application code as shown in the below image. I double-click on the EXE three times, so three external threads are accessing our application at the same time.

External Threads Executing our Application Code

But, if you want to restrict that only external thread access to our application code at any given point in time, then we need to use the Mutex in C#. Let us rewrite the example using Mutex and see what happens we try to access the application code multiple times from outside using External Threads and then we will discuss the C# Mutex Class in detail.

Modify the code as follows. So, when one external access to our code, no more external thread can access the code. The following example exactly does the same using Mutex. This is one of the use cases of Mutex in C#.

using System;
using System.Threading;

namespace MutexDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            using(Mutex mutex = new Mutex(false, "MutexDemo"))
            {
                //Checking if Other External Thread is Running
                if(!mutex.WaitOne(5000, false))
                {
                    Console.WriteLine("An Instance of the Application is Already Running");
                    Console.ReadKey();
                    return;
                }
                Console.WriteLine("Application Is Running.......");
                Console.ReadKey();
            }
        }
    }
}

Now close all the instances which are running. Then build the project and again go to the projects bin\Debug directory and again click on the Exe file for the first time. You will get the following result.

Understanding Mutex in C#

Now, again click on the EXE file. This time it will wait for 5 seconds and then it will give you the following message. This ensures that only one external thread can access our application code at any given point in time.

Mutex in C# with Examples

Now, I hope you understand the need for Mutex in C#. Let us proceed further and understand the Mutex Class in C# with multiple examples.

What is Mutex in C#?

Mutex works like 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 in time, only one thread can enter into the critical section.

When two or more threads need to access a shared resource at the same time, the system needs a synchronization mechanism to ensure that only one thread at a time uses the resource. Mutex is a synchronization primitive that grants exclusive access to the shared resource to only one thread. If a thread acquires a mutex, the second thread that wants to acquire that mutex is suspended until the first thread releases the mutex.  If this is not clear at the moment then don’t worry, we try to understand this with some examples.

Constructors, and Methods of Mutex Class in C#:

Let us understand the different Constructors, and Methods of Mutex Class in C#. If you right-click on the Mutex class and select go to definition, then you will see the following that the Mutex is a sealed class and it inherited from WaitHandle class.

Constructors, and Methods of Mutex Class in C#

Constructors of Mutex Class in C#:

The Mutex Class in C# provides the following five constructors that we can use to create an instance of the Mutex class.

  1. Mutex(): It initializes a new instance of the Mutex class with default properties.
  2. Mutex(bool initiallyOwned): It initializes a new instance of the Mutex class with a Boolean value that indicates whether the calling thread should have initial ownership of the mutex.
  3. Mutex(bool initiallyOwned, string name): It initializes a new instance of the System.Threading.Mutex class with a Boolean value that indicates whether the calling thread should have initial ownership of the mutex, and a string that is the name of the mutex.
  4. Mutex(bool initiallyOwned, string name, out bool createdNew): It initializes a new instance of the System.Threading.Mutex class with a Boolean value that indicates whether the calling thread should have initial ownership of the mutex, a string that is the name of the mutex, and a Boolean value that, when the method returns, indicates whether the calling thread was granted initial ownership of the mutex.
  5. Mutex(bool initiallyOwned, string name, out bool createdNew, MutexSecurity mutexSecurity): It initializes a new instance of the System.Threading.Mutex class with a Boolean value that indicates whether the calling thread should have initial ownership of the mutex, a string that is the name of the mutex, and a Boolean variable that, when the method returns, indicates whether the calling thread was granted initial ownership of the mutex, and the access control security to be applied to the named mutex.

Following are the parameters used in the Constructors of Mutex Class in C#.

  1. initiallyOwned: true to give the calling thread initial ownership of the named system mutex if the named system mutex is created as a result of this call; otherwise, false.
  2. name: The name of the Mutex. If the value is null, the Mutex is unnamed.
  3. createdNew: When this method returns, contains a Boolean that is true if a local mutex was created (that is, if the name is null or an empty string) or if the specified named system mutex was created; false if the specified named system mutex already existed. This parameter is passed uninitialized.
  4. mutexSecurity: A System.Security.AccessControl.MutexSecurity object that represents the access control security to be applied to the named system mutex.
Methods of Mutex Class in C#:

The Mutex Class in C# provides the following methods.

  1. OpenExisting(string name): This method is used to open the specified named mutex if it already exists. It returns an object that represents the named system mutex. Here, the parameter name specifies the name of the system mutex to open. It will throw ArgumentException if the name is an empty string. -or- name is longer than 260 characters. It will throw ArgumentNullException if the name is null.
  2. OpenExisting(string name, MutexRights rights): This method is used to open the specified named mutex, if it already exists, with the desired security access. It returns an object that represents the named system mutex. Here, the parameter name specifies the name of the system mutex to open. The parameter rights specify a bitwise combination of the enumeration values that represent the desired security access.
  3. TryOpenExisting(string name, out Mutex result): This method is used to open the specified named mutex, if it already exists, and returns a value that indicates whether the operation succeeded. Here, the parameter name specifies the name of the system mutex to open. When this method returns, the result contains a Mutex object that represents the named mutex if the call succeeded, or null if the call failed. This parameter is treated as uninitialized. It returns true if the named mutex was opened successfully; otherwise, false.
  4. TryOpenExisting(string name, MutexRights rights, out Mutex result): This method is used to open the specified named mutex, if it already exists, with the desired security access, and returns a value that indicates whether the operation succeeded. Here, the parameter name specifies the name of the system mutex to open. The parameter rights specify a bitwise combination of the enumeration values that represent the desired security access. When this method returns, the result contains a Mutex object that represents the named mutex if the call succeeded, or null if the call failed. This parameter is treated as uninitialized. It returns true if the named mutex was opened successfully; otherwise, false.
  5. ReleaseMutex(): This method is used to release Mutex once.
  6. GetAccessControl(): This method gets a System.Security.AccessControl.MutexSecurity object that represents the access control security for the named mutex. It returns a System.Security.AccessControl.MutexSecurity object that represents the access control security for the named mutex.
  7. SetAccessControl(MutexSecurity mutexSecurity): This method is used to set the access control security for a named system mutex. The parameter mutexSecurity specifies a System.Security.AccessControl.MutexSecurity object that represents the access control security to be applied to the named system mutex.

Note: The Mutex Class in C# is inherited from WaitHandle class and the WaitHandle class provides the WaitOne() method which we need to call to lock the resource. Note that a Mutex can only be released from the same thread which obtained it.

Example to Understand Mutex in C# to Protect Shared Resource in Multithreading:

The following example shows how a local Mutex object is used to synchronize access to a protected resource. Because each calling thread is blocked until it acquires ownership of the mutex, it must call the ReleaseMutex method to release ownership of the mutex. 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)
                {
                    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 can enter  
                mutex.ReleaseMutex();
            }
        }
    }
}
Output:

Example to Understand Mutex in C# to Protect Shared Resource in Multithreading

In the following example, each thread calls the WaitOne(Int32) method to acquire the mutex. If the time-out interval elapses, the method returns false, and the thread neither acquires the mutex nor gains access to the resource the mutex protects. The ReleaseMutex method is called only by the thread that acquires the mutex.

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 <= 3; i++)
            {
                Thread threadObject = new Thread(MutexDemo)
                {
                    Name = "Thread " + i
                };
                threadObject.Start();
            }
            Console.ReadKey();
        }

        //Method to implement syncronization using Mutex  
        static void MutexDemo()
        {
            // Wait until it is safe to enter, and do not enter if the request times out.
            Console.WriteLine(Thread.CurrentThread.Name + " Wants to Enter Critical Section for processing");
            if (mutex.WaitOne(1000))
            {
                try
                {
                    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 can enter  
                    mutex.ReleaseMutex();
                    Console.WriteLine(Thread.CurrentThread.Name + " Has Released the mutex");
                }
            }
            else
            {
                Console.WriteLine(Thread.CurrentThread.Name + " will not acquire the mutex");
            }
        }

        ~Program()
        {
            mutex.Dispose();
        }
    }
}
Output:

Mutex in C# to Protect Shared Resources in Multithreading

OpenExisting Method Example of Mutex Class in C#:

In the below example we use the OpenExisting method of the Mutex Class in C#. If this method throws an exception, the specified named Mutex does not exist or is inaccessible. The IsSingleInstance method uses this behavior. First, create a console application and copy and paste the following code.

using System;
using System.Threading;
namespace MutexDemo
{
    class Program
    {
        static Mutex _mutex;

        static bool IsSingleInstance()
        {
            try
            {
                // Try to open existing mutex.
                Mutex.OpenExisting("MyMutex");
            }
            catch
            {
                // If exception occurred, there is no such mutex.
                _mutex = new Mutex(true, "MyMutex");

                // Only one instance.
                return true;
            }

            // More than one instance.
            return false;
        }

        static void Main()
        {
            if (!IsSingleInstance())
            {
                Console.WriteLine("More than one instance"); // Exit program.
            }
            else
            {
                Console.WriteLine("One instance"); // Continue with program.
            }
            // Stay open.
            Console.ReadLine();
        }
    }
}

Now, build the project and then go to the projects bin\Debug directory and click on the Application EXE file three times and you will get the following results.

Mutex.OpenExisting Method Example in C#

Note: Mutex only allows one external thread to access our application code. But if we want more control over the number of external threads to access our application code, then we need to use Semaphore in C#.

In the next article, I am going to discuss the use of Semaphore Class in C# with Examples. Here, in this article, I try to explain How to use Mutex in C# to Protect Shared Resources in Multithreading with Examples. I hope you enjoy this Mutex Class in C# with Examples article.

2 thoughts on “Mutex Class in C#”

  1. blank

    Guys,
    Please give your valuable feedback. And also, give your suggestions about the Mutex Class in C#. If you have any better examples, you can also put them in the comment section. If you have any key points related to C# Mutex Class, you can also share the same.

  2. blank

    hello,
    Thanks for this tutorial.
    I want to ask, in the second example why is this not work if we made this changes
    using (var mutex = new Mutex(false, “MutexDemo”))
    {
    //Checking if Other External Thread is Running
    if(!mutex.WaitOne(5000, false))
    {
    Console.WriteLine(“An Instance of the Application is Already Running”);
    return;
    }
    Console.WriteLine(“Application Is Running new…….”);
    }
    Console.ReadKey();

    Regarding

Leave a Reply

Your email address will not be published.