How to use Mutex in C# to Protect Shared Resources in Multithreading

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.

public static class MutexSample
{
    public static void Exeute()
    {
        for (int i = 0; i < 5; i++)
        {
            Thread doWorkThread = new Thread(new ParameterizedThreadStart(doWork));
            doWorkThread.Start(i);
        }

        Console.ReadLine();
    }

    //Mutex(mutual exclusion) is very similar to lock/Monitor. The difference is that it can work across multiple processes.
    //Make mutex. 
    private static Mutex mutex = new Mutex();

    private static void doWork(object threadNumber)
    {
        try
        {
            //The code will stop executing here and wait until the lock is released by the previous thread. 
            mutex.WaitOne();

            Console.WriteLine("Thread " + threadNumber.ToString() + " has started.");

            //Simulate doing time consuming work.
            Thread.Sleep(1500);

            Console.WriteLine("Thread " + threadNumber.ToString() + " is done.");
        }
        finally
        {
            //Realesase the lock so other threads can now get access.
            mutex.ReleaseMutex();
        }
    }
}

Comments

Leave a Comment

All fields are required. Your email address will not be published.