Running Single Instance of the Application

You've built an application and would like it to run a single instance. Here comes Mutex to the rescue! To do that you have to create a Mutex object at startup and when its over release it.

First add System.Threading namespace:

using System.Threading;

Then create a boolean variable and a Mutex object to control if Mutex is owned by application
 

bool isMutexOwned;

Mutex mut = null;

Then create a Mutex instance and control this Mutex via isMutexOwned boolean var.

using(Mutex mut=new Mutex(true,"My Mutex",out isMutexOwned))
{
   if(isMutexOwned)
   {
     
//Do Something...Mutex is owned by the application
   }
  
else
   {
     
//Mutex isnt owned.So other instances can run.
   }
}
 

public void ReleaseMut()
{
  mut.ReleaseMutex();
}


Add a Button Click event and raise ReleaseMut function. See what happens.
After that another instance of application will now run.


Similar Articles