Forcing a single instance of a process in .Net with Mutex

March 14, 2012
Forcing a single instance of a process in .Net with Mutex

In a recent application, a requirement was to allow for only a single instance to be running at a time. Typically I would do this with Systems.Diagnostics.Process and search for an instance of my running application, but I wanted to try the Mutex method because it appeared to be simpler and a bit lighter.A Mutex is a synchronization primitive that can be used for interprocess synchronization while most other locking mechanisms are process specific. You can read more about Mutex here</>.It turned out to be much simpler than I had expected, so I thought I would share how to set it up in a Windows Form project. The first step is to add a class with some native methods that are required to bring the application to the top if it is already running.[sourcecode language="csharp"]class NativeMethods{ public const int HWND_BROADCAST = 0xffff; public static readonly int WM_SHOWME = RegisterWindowMessage("WM_SHOWME"); [DllImport("user32")] public static extern bool PostMessage(IntPtr hwnd, int msg, IntPtr wparam, IntPtr lparam); [DllImport("user32")] public static extern int RegisterWindowMessage(string message);}[/sourcecode]The next step is to define the Mutex that will be used to identify the process.[sourcecode language="csharp"]static class Program{ private static readonly Mutex mutex = new Mutex(true, "{5D562B9B-8B2B-4A30-979A-083BDE97B99E}"); ...[/sourcecode]The Mutex.WaitOnce method provides the magic for checking if our process is already running. It has an overload that takes two parameters; Time to wait and a Boolean for exiting the context. WaitOnce returns true if it is able to enter and false if it is not. So, with the following, we can launch the application if it is not already open.[sourcecode language="csharp"]if (mutex.WaitOne(TimeSpan.Zero, true)){ Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1());</p>}[/sourcecode]And in the else block the existing process can be brought to the top of the display.[sourcecode language="csharp"]if (mutex.WaitOne(TimeSpan.Zero, true)){ Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); mutex.ReleaseMutex();</p>}else{ NativeMethods.PostMessage( (IntPtr)NativeMethods.HWND_BROADCAST, NativeMethods.WM_SHOWME, IntPtr.Zero, IntPtr.Zero);</p>}[/sourcecode]So there you have it. The application will only allow for one instance and will be brought to the front of the display if a user attempts to launch it while it is running.