Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run single instance of an application using Mutex

Tags:

c#

mutex

In order to allow only a single instance of an application running I'm using mutex. The code is given below. Is this the right way to do it? Are there any flaws in the code?

How to show the already running application when user tries to open the application the second time. At present (in the code below), I'm just displaying a message that another instance is already running.

    static void Main(string[] args)     {         Mutex _mut = null;          try         {             _mut = Mutex.OpenExisting(AppDomain.CurrentDomain.FriendlyName);         }         catch         {              //handler to be written         }          if (_mut == null)         {             _mut = new Mutex(false, AppDomain.CurrentDomain.FriendlyName);         }         else         {             _mut.Close();             MessageBox.Show("Instance already running");          }                 } 
like image 330
blitzkriegz Avatar asked May 04 '09 11:05

blitzkriegz


People also ask

How to make single instance application in c#?

Console ApplicationWhen we run the application, a Mutex object with a unique identifier (the appName in this case) is created. The constructor takes 3 arguments, with the 3rd being the most important. This output parameter simply tells us whether other objects with the same identifier was already created.

How do I run a single instance of the application using Windows Forms?

" This feature is already built in to Windows Forms. Just go to the project properties and click the "Single Instance Application" checkbox. "

What is single instance application?

A Single Instance application is an application that limits the program to run only one instance at a time. This means that you cannot open the same program twice.


2 Answers

I did it this way once, I hope it helps:

bool createdNew;  Mutex m = new Mutex(true, "myApp", out createdNew);  if (!createdNew) {     // myApp is already running...     MessageBox.Show("myApp is already running!", "Multiple Instances");     return; } 
like image 156
Peter D Avatar answered Sep 19 '22 16:09

Peter D


static void Main()  {   using(Mutex mutex = new Mutex(false, @"Global\" + appGuid))   {     if(!mutex.WaitOne(0, false))     {        MessageBox.Show("Instance already running");        return;     }      GC.Collect();                     Application.Run(new Form1());   } } 

Source : http://odetocode.com/Blogs/scott/archive/2004/08/20/401.aspx

like image 40
Milen Avatar answered Sep 17 '22 16:09

Milen