Use named Mutex to restrict multiple program startup

Something new I had learn from C# today, and that is, the use of Mutex.

I guess most people know what is mutex. For clarity, below is the Mutex definition from Microsoft

When two or more threads need to access a shared resource at the same time, the system needs a synchronization mechanism to ensure that only one thread at a time uses the resource. Mutex is a synchronization primitive that grants exclusive access to the shared resource to only one thread. If a thread acquires a mutex, the second thread that wants to acquire that mutex is suspended until the first thread releases the mutex.

But, there is 2 types of Mutex, local and system-wide. Local Mutex is a unnamed mutex that only avaiable for the created process. System-wide Mutex is a named mutex that available for the whole operation system.

Definition from Microsoft

Mutexes are of two types: local mutexes, which are unnamed, and named system mutexes. A local mutex exists only within your process. It can be used by any thread in your process that has a reference to the Mutex object that represents the mutex. Each unnamed Mutex object represents a separate local mutex.
Named system mutexes are visible throughout the operating system, and can be used to synchronize the activities of processes. You can create a Mutex object that represents a named system mutex by using a constructor that accepts a name. The operating-system object can be created at the same time, or it can exist before the creation of the Mutex object. You can create multiple Mutex objects that represent the same named system mutex, and you can use the
OpenExisting method to open an existing named system mutex.

By creating a system-wide mutex, you can restrict a multiple startup of your program.


bool ok;
mutex = new Mutex(true, "Your-Mutex-Name", out ok);



Using Mutex(Boolean, String, Boolean) constructor, it will try to create a system-wide mutex with Your-Mutex-Name and request initial ownship for the calling thread. On method return, ok boolean will indicates whether the calling thread was granted initial ownership of the mutex. So, to prevent multiple program startup, all you need is to check if(ok == false), when that occurs, exit the program.


GC.KeepAlive(mutex);


The above is important to tell VM not to clear the mutex as long as the program is running. Put that after Application.run() will do.

See http://msdn.microsoft.com/en-us/library/system.threading.mutex.aspx

Comments

Popular Posts