Previously I used the Process class to find out if a process with the same name is already running. Here is the link.
But that method had a problem. The code could easily be dodged by renaming the assembly. The Process class would give a different name the next time and a new instance will be started.
Now I have come up with the mutex which is much safer. Every time the application is started we check for a certain mutex. If the mutex exists we error out. Otherwise we go ahead, create that special mutex for our successors and run the application. Dont forget to release that mutex when application is about to exit.
try { SingleInstanceMutex = Mutex.OpenExisting("TickerMutex0"); Process.GetCurrentProcess().Kill(); } catch (Exception ex) { SingleInstanceMutex = new Mutex(false, "TickerMutex0"); }
If the OpenExisting method fails to open it will throw an exception which is fine. We create the mutex in this case and go on. And if a valid mutex is found, we simply close. The SingleInstanceMutex is a private member of the class of System.Threading.Mutex type. The Mutex is released when application is closed so we need to catch the Application_Exit event.
Application.ApplicationExit += new EventHandler(Application_ApplicationExit);
The body of Application_ApplicationExit function is:
void Application_ApplicationExit(object sender, EventArgs e) { try { SingleInstanceMutex.ReleaseMutex(); } catch (Exception ex) { MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
I am using the Process.Kill method here because there is some special code in Application_Exit event which I dont want to run everytime.


3 responses so far ↓
hashfactor // February 2, 2009 at 9:48 am
Thanks to Bogdan Seceleanu who pointed out the problem
http://hashfactor.wordpress.com/2009/01/29/c-winforms-disallow-multiple-instances-of-your-application/
Andrew // August 27, 2009 at 7:59 am
You might want to look at: http://www.hanselman.com/blog/TheWeeklySourceCode31SingleInstanceWinFormsAndMicrosoftVisualBasicdll.aspx
There is also a great alternative in there from a user comment that uses Mutex’s: http://www.flawlesscode.com/post/2008/02/Enforcing-single-instance-with-argument-passing.aspx
Andrew // August 27, 2009 at 8:01 am
Although in hindsight that’s Win Forms specific, perhaps not necessarily of interest to your article…