Introduction
This article outlines a way to prevent multiple instances of an application running on a machine, using the Mutex
class, in situations where Application.Restart
gets called.
Background
The current application I am working on requires that only one instance be running on any one machine at any time, a reasonably common requirement. It seems the two main ways to accomplish this involve iterating through the running processes or creating a Mutex. However, the application I work with restarts itself in several situations (using Application.Restart
). In the majority of cases, Application.Restart
will start a new instance of the application before the old AppDomain has finished closing. Without allowing a timeout on the lock of the Mutex, the new instance will not start, and the old instance will finish closing, leaving you with nothing running.
Code
static Mutex _mutex = new Mutex(false, "mutexName");
[STAThread]
static void Main()
{
if (!_mutex.WaitOne(1000, false))
return;
_mutex.ReleaseMutex();