65.9K
CodeProject is changing. Read more.
Home

Preventing Multiple Application Instances When Using Application.Restart

starIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIconemptyStarIcon

1.63/5 (15 votes)

Apr 29, 2008

CPOL
viewsIcon

34941

Use the Mutex class with a timeout to prevent more than one instance of an application running in a situation where Application.Restart is being called.

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

// Declare the Mutex. If it exists we get a reference to the existing one
// if not, the OS will create a new one. 
// false indicates we do not want initial ownership of the mutex
// mutexName is the unique name of the mutex
static Mutex _mutex = new Mutex(false, "mutexName");

[STAThread]
static void Main()
{
   // WaitOne will return true if it is able to lock the Mutex and false if the mutex
   // has already been locked by another instance of the application.
   // 1000 is the timeout in milliseconds - this is what gives the old instance of 
   // the application time to shut down and is arbitrary.
   // the boolean specifies whether to exit the synchronization domain before the wait
   if (!_mutex.WaitOne(1000, false))
      return;


   // Application code in here


   // This is required so that other instances can now lock the Mutex.
   _mutex.ReleaseMutex();