All posts tagged mutex

If you arrived here chances are you have a WPF application you want to lock down to running only once. Maybe you tried doing it by looking at Process.GetProcesses() but found it to be slow and unreliable and wanted something a bit more straight forward? Well, mutexes would be the most direct way to go. There are a few articles on the web about how to do this in .Net and they go into great detail about how mutexes work and how developers misuse them all the time. I am going to touch on the pieces you need for this solution and not waste any more of your time.

Q: What is a mutex?
A: If you took Computer Science courses this should be a no-brainer, but let’s assume you didn’t.

Mutex is short for a mutual exclusion object. This exists as a uniquely named resource that can be shared across multiple threads. Each thread would need to lock the resource to use it, so it cannot be accessed simultaneously.

Q: How does this help me?
A: Multiple applications can access the mutex allowing you to create a unique token to be reserved by a specific application instance.

Now we get to the how part.
First, let create a mutex placeholder and a unique key for our mutex:


private static Mutex _instanceMutex;
private static string MyApplicationKey = "{0036BC97-7DE3-4934-9928-43CE53CBF0AA}";

Next let’s create some key methods to set, evaluate, and terminate our mutex:


/// <summary>
/// Checks if application is already running.
/// </summary>
/// <returns></returns>
public static bool StartInstance()
{
    // Set mutex
    _instanceMutex = new Mutex(true, Constants.MyApplicationKey);

    // Check if already running
    bool isAlreadyInUse = false;
    try 
    {
        isAlreadyInUse = !_instanceMutex.WaitOne(TimeSpan.Zero, true);
    }
    catch (AbandonedMutexException)
    {
        KillInstance();
        isAlreadyInUse = false;
    }
    catch (Exception)
    {
        _instanceMutex.Close();
        isAlreadyInUse = false;
    }
    return isAlreadyInUse;
}

/// <summary>
/// Kills the instance.
/// </summary>
/// <param name="code">The code.</param>
public static void KillInstance(int code = 0)
{
    if (_instanceMutex == null) return;

    // Owning application should release mutex
    if (code == 0)
    {
        try
        {
            _instanceMutex.ReleaseMutex();
        }
        catch (Exception) { }
    }
    _instanceMutex.Close();
}

StartInstance does a few key things:

  • Claim ownership of a new mutex with our application key.
  • Evaluate the mutex by invoking a WaitHandle.
  • An AbandonedMutexException exception may occur which means the mutex exists but was not properly released by the owning process. This is likely caused by the owning process exiting unexpectedly. We kill the mutex in this case (covered later) and set this as not in use.
  • If a general exception occurs we simply close the instance and set it to not in use.
  • Otherwise, it is already in use.

 
Hold on a second!

Q: What is the difference between Releasing a mutex and Closing a mutex?
A: This is an important question.

Releasing a mutex (Mutex.ReleaseMutex()) releases a mutex from memory. This means no application can access it and it will need to be created again. Only the owning application can release the mutex unless that application is no longer in memory.

Closing a mutex (Mutex.Close()) in .Net really means closing the WaitHandle associated with the mutex. This should always be done after accessing a mutex.

 
KillInstance works as follows:

  • If a standard exit code of 0 is provided it assumes itself the owner of the mutex and attempts to release it.
  • The mutex is then closed.

 
And that’s all you need. So, let’s put it in an example.

Let’s add it to our App.xaml.cs OnStartup and OnExit as follows:


/// <summary>
/// Raises the <see cref="E:System.Windows.Application.Startup" /> event.
/// </summary>
/// <param name="e">A <see cref="T:System.Windows.StartupEventArgs" /> that contains the 
/// event data.</param>
protected override void OnStartup(StartupEventArgs e)
{
    base.OnStartup(e);

    // Check if running
    if (!StartInstance()) return;
    
	// Apparently we are already running our app
    MessageBox.Show("Already Running!");

    // If running, peace out
    Application.Current.Shutdown(1);
}

/// <summary>
/// Raises the <see cref="E:System.Windows.Application.Exit"/> event.
/// </summary>
/// <param name="e">An <see cref="T:System.Windows.ExitEventArgs"/> that contains the event 
/// data.</param>
protected override void OnExit(ExitEventArgs e)
{
    base.OnExit(e);

    // Kill instance
    KillInstance(e.ApplicationExitCode);
}

  1. OnStartup evaluates whether the mutex is already in use. If it is, it tells the user it is already running and exits the application.
  2. OnExit passes the exit code to KillInstance and handles closing the mutex.

 
And that’s it! I recommend you read up more on mutexes to make absolutely sure you are comfortable with this approach. But for now, this should get you what you need to get back to work.

Happy coding!