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 ReleaseMutex
.
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 seasoned software consultant and technologist based in Brisbane, Australia. I've been helping businesses reach their digital ambitions in the fast-paced tech world for about 15 years.
With expertise in people leadership, software architecture and craftsmanship, the Microsoft ecosystem, web technologies, C#, ASP.NET, and Azure, I team up with organisation leaders to bring their visions to life. My passion lies in making a positive impact through technology.
Outside of my profession, you can catch me diving into self-development, breathwork, fitness, travelling, fishing, camping and making random noises with the flamenco guitar.