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, 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.
I'm a software consultant, tech lead, servant team lead, C♯ and .NET aficionado, occasional public speaker, gardener, camping enthusiast and certified PSM I based in Brisbane, AU. I'm passionate about making positive impacts through technology, good software craftsmanship practices and effective project management.
Being a consultant exposes me to a wide variety of challenges, both technical and non-technical, and results in diverse and invaluable learning. This blog's main purpose is to serve as a self-reminder of some of those learnings that I've found the time to write down, but if it happens to help you too, that's even better!