Updated on 2020-05-01
This tip demonstrates how to create an app that only allows one instance to run at a time
Occasionally, it's desirable to create an application that only allows for one instance to run. This tip shows you one such method using a systemwide named mutex to check for another instance.
The idea here is very simple. We wrap the entry point method with a creation or opening of a named mutex which exists across the entire OS, and all applications. We check the creation method to see if a new mutex was indeed created and if not, we can know that another instance is already running and exit.
Accomplishing the above is very simple. Here is the demo code in its entirety.
using System;
using System.Reflection;
using System.Threading;
namespace SingletonMutex
{
class Program
{
static void Main()
{
var appName = Assembly.GetEntryAssembly().GetName().Name ;
var notAlreadyRunning = true;
using (var mutex = new Mutex(true, appName + "Singleton", out notAlreadyRunning))
{
if (notAlreadyRunning)
{
// do work here:
Console.WriteLine("Running. Press any key to exit...");
Console.ReadKey();
}
else
Console.Error.WriteLine(appName + " is already running.");
}
}
}
}
The code above will work in any console application, and can easily be adapted to a Windows Forms or WPF application.
We need to pass a string that's unique to the application to the Mutex constructor for it to be system wide. Here, simply concatenate the assembly's filename with "Singleton".
Inside the using block, we simply check if a new mutex was created or already exists, which is what the notAlreadyRunning variable indicates. If it's true, we do our work. If it's false, we simply exit. That's where you'd put your own application code.
You can test the application in Visual Studio by doing Ctrl+F5 twice to run two instances.