What is the Mutex class in C#?


The Mutex class in C# is a synchronization primitive that can also be used for interprocess synchronization.

Let us see how to create a new Mutex.

private static Mutex m = new Mutex();

Let us now see how to initialize a new instance of the Mutex class with a Boolean value.

private static Mutex m = new Mutex(true);

Now let us see how to initialize a new instance of the Mutex class with a Boolean value and the name of the Mutex.

Example

 Live Demo

using System;
using System.Threading;

public class Demo {
   public static void Main() {
      Mutex mt = new Mutex(false, "NewMutex");
      Console.WriteLine("Waiting for the Mutex.");
      mt.WaitOne();
      Console.WriteLine("Owner of the mutex. " + "ENTER is to be pressed to release the mutexand          exit.");
      Console.ReadLine();
      mt.ReleaseMutex();
   }
}

Output

Waiting for the Mutex.
Owner of the mutex. ENTER is to be pressed to release the mutex and exit.

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 22-Jun-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements