How to restrict a program to a single instance

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#?


Solution 1:

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
     }
  }

Solution 2:

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.

Solution 3:

There are many ways, such as -

  • Enumerating list of processes before starting and denying the startup if process name already exists.
  • Creating a mutex on startup and checking if mutex already exists.
  • Launching a program through a singleton class.

Each is demoed below:

http://iridescence.no/post/CreatingaSingleInstanceApplicationinC.aspx
http://www.codeproject.com/KB/cs/restricting_instances.aspx
http://www.codeproject.com/KB/cs/singleinstance.aspx

Each has its pros and cons. But I believe the creating mutex is the best one to go for.