Allowing only one instance of a C# application to run
Making a singleton application, i.e. preventing users from opening multiple instances of your app, is a common requirement which can be easily implemented using a Mutex.
A Mutex is similar to a C# lock, except it can work across multiple processes, i.e. it is a computer-wide lock. Its name comes from the fact that it is useful in coordinating mutually exclusive access to a shared resource.
Let’s take a simple Console application as an example:
Using a Mutex, we can change the above code to allow only a single instance to print
Hello World! and the subsequent instances to exit immediately:
Note that we’ve passed
false for the
initiallyOwned parameter, because we want to create the mutex in a signaled/ownerless state. The
WaitOne call later will try to put the mutex in a non-signaled/owned state.
Once an instance of the application is running, the
saebamini.com SingletonApp Mutex will be owned by that instance, causing further
WaitOne calls to evaluate to false until the running instance relinquishes ownership of the mutex by calling
Keep in mind that only one thread can own a Mutex object at a time, and just as with the lock statement, it can be released only from the same thread that has obtained it.