Single .NET Application Instance using Named Mutexes

I had a problem today where I needed to ensure that only one instance of a particular C# application was running. After trying some arcane methods, like using files or probing the Process list, I remembered a technique was back when I was programming in the WinAPI: Using Mutexes.

Here’s the general workflow. A named mutex in Windows is system-wide (as far as I know). So, one of the first things my application does is to create a mutex object. I happen to do this during static initialization:

using System;
using System.Threading;


public class EntryPoint
{
 static Mutex mutex = new Mutex(false, "MyApplicationMutex");

 ...

}

Now, inside the Main method, I would need attempt to wait using the WaitOne() method. But, I want this method to return right away instead of blocking, so I specify the timeout parameter to 0. The return value will tell me whether the my process was signaled or not. If it has not been signaled, this means that there is another process using the mutex. So, code-wise:

...

if (!mutex.WaitOne(0, false)) 
{
 Console.Error.WriteLine("Application is already running.  This 

process will exit!");
 return;
}

...

Finally, I need to ensure that the mutex is properly released:

...

 mutex.ReleaseMutex();

...

Viola!



%d bloggers like this: