Sunday, 1 April 2007

Use Mutex class to ensure only one instance of an application is running

Mutex class is an operating system level class to provide a data locking mechanism in multi-threading application. It works by locking data across AppDomain and process boundaries. Thus this class is ideal to ensure only one instance of an application is running.

In the Main() function of Progam.cs, add this piece of code will ensure one instance of an application, because the MutexName is shared across application domains.

Mutex one = null;
const string MutexName = "RunOnce";
try
{
one = Mutex.OpenExisting(MutexName);
}
catch (WaitHandleCannotBeOpenedException)
{
}

if (one == null)
{
one = new Mutex(true, MutexName);
}
else
{
one.Close();
return;
}