Hash

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

February 2, 2009 · 3 Comments

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.

Categories: .NET
Tagged: , , , , , , , , ,

3 responses so far ↓

Leave a Comment