I have a console application in C# and I want to restrict my application to run only one instance at a time. How do I achieve this in C#?
If you want to limit the application to one instance per machine (i.e. not one per logged on user), then you will need your mutex name to start with the prefix Global\ . If you don't add this prefix, a different instance of the mutex will be created by the OS for each user.
Using singleton, that is a class which only allows a single instance of itself to be created. The operation of this pattern is simple and could be reduced to the following: Hide the constructor of the Singleton class, so that clients may not be instantiated.
A Single Instance application is an application that limits the program to run only one instance at a time. This means that you cannot open the same program twice.
I would use a Mutex
static void Main() { string mutex_id = "MY_APP"; using (Mutex mutex = new Mutex(false, mutex_id)) { if (!mutex.WaitOne(0, false)) { MessageBox.Show("Instance Already Running!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Hand); return; } // Do stuff } }
If you decide to use a Mutex for that purpose, there are some pitfalls you should be aware of:
If you want to limit the application to one instance per machine (i.e. not one per logged on user), then you will need your mutex name to start with the prefix Global\
. If you don't add this prefix, a different instance of the mutex will be created by the OS for each user.
If you are running on a Windows Vista or later machine with UAC enabled, and by some chance the current application instance is running as an admin, then the next instances will fail detecting it, and you will get permission exceptions. To avoid this you need to specify a different set of permissions for the Mutex when creating it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With