Monday, January 25, 2016

Mutex in .NET

Mutex means mutual exclusion. Mutex is class in .NET framework. It is thread synchronization process. Mutex is used to prevent the execution of a shared resource by multiple threads. It allows only one single thread to enter to execute a particular task. It is used in single process or multiple processes. It can also be used for inter process synchronization. Monitor/Lock prevents shared resource from internal threads, but Mutex prevent from both internal as well as external threads. In another way we can say, mutex provide thread safety against internal/external threads. 

 Example: Multiple threads are writing to file in this example.
 I have synchronization multiple thread using mutex. Only one thread is accessing shared 
resource (file here) at a time.

using System;
using System.Threading;
using System.IO;

class ConsoleApplication1
{
    static void Main(string[] args)
    {
        for (int i = 0; i < 5; i++)
        {
            Thread thread = new Thread(new ThreadStart(Go));
            thread.Name = String.Concat("Thread ", i);
            thread.Start();
        
        }
        Console.ReadLine();
    }

    static void Go()
    {
        Thread.Sleep(500);
        WriteFile();
    }

    static Mutex mutex = new Mutex();
    static void WriteFile()
    {
        mutex.WaitOne();

        String ThreadName = Thread.CurrentThread.Name;
        Console.WriteLine("{0} using resource", ThreadName);

        try
        {
            using (StreamWriter sw = new StreamWriter("C:\\abc.txt", true))
            {
                sw.WriteLine(ThreadName);
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }

        Console.WriteLine("{0} releasing resource", ThreadName);

       mutex.ReleaseMutex();
    }   

Handling single Instance of Application:

namespace ConsoleApplication1
{
    class SingleInstance
    {
        static void Main(string[] args)
        {
            String appGUID=”5a913d2e-1d4b-492c-a408-df315ca3de93”;
            bool ok;
            Mutex mutex = new System.Threading.Mutex(true, appGUID, out ok);

            if (!ok)
            {
                Console.WriteLine("Another instance is already running.");
            }
            else
            {
                Console.WriteLine("Single instance is running.");
            }
                    
             Console.ReadLine();
        }
    }
}

When application will be launched first time, you can see below message.

 

When application is launched more than 1 times then you will see below message.
 
Note:
            1. The name of the mutex should be a unique  either assembly name or GUID. 
         2.  Mutex hits performance, so it should be used when synchronization across 
              process boundaries is required.
            3.  A mutex can also be passed across application domain boundaries.

Write a program to reverse a string? using System; namespace ConsoleApp1 {     class Program     {         static void Main(string[] args)  ...