What is the Mutex class in C#?

CsharpProgrammingServer Side Programming

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.
raja
Published on 21-Aug-2018 07:58:52
Advertisements