C#: Disallow multiple instances of your application. The Mutex way.

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.

Advertisements

3 thoughts on “C#: Disallow multiple instances of your application. The Mutex way.

  1. Or you could try:

    int myProcessID = Process.GetCurrentProcess().Id;
    string name = “Process_Name”;
    foreach (Process clsProcess in Process.GetProcesses())
    {
    if (clsProcess.ProcessName.StartsWith(name))
    {
    if (clsProcess.Id != myProcessID)
    {
    clsProcess.Kill();
    }
    }
    }

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s