Aug 5, 2015

Mutex In Csharp

Mutex stands for mutual exclusion. The Mutex type ensures blocks of code are executed only once at a time. It can create named mutexes that can be opened by other processes. With it, we ensure only one instance is run on the computer.

Example. This simple example uses the Mutex.OpenExisting method. If the OpenExisting method throws an exception, the specified named Mutex does not exist or is inaccessible. The IsSingleInstance method uses this behavior.
And: If the Mutex does not exist, it creates a new one. Further instances of the program then can tell that an instance is already open.

C# program that uses Mutex and OpenExisting

using System;
using System.Threading;

class Program
{
    static Mutex _m;

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

     // Only one instance.
     return true;
 }
 // More than one instance.
 return false;
    }

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

Result

1. First execution will display "One instance"
2. Second execution will display "More than one instance"
3. Third execution is the same as second.

No comments:

Post a Comment