C#: Having One Instance Of an Running Application Using A Mutex in System.Threading

(Updated April/9/2011: Removed bad highlight colors, made title more descriptive and reworked wording of the text.)

The following C# code effectively allows for only one instance of an application to run and can be used with any version of .Net.

By using and checking the status of a named mutex the code is assured that another instance is running if its status comes back as valid. Do not check and throw away the mutex for the caveot to doing this is that the mutex could be garbaged collected if not properly held for the lifetime of the application and once the mutex is released another program checking will not find it.

Place a reference to the mutex on an existing long running class or in a static instance in your prgram.

Here is the code, it is demonstrated to run in a console application and the System.Threading namespace must be used:

bool NoInstanceCurrently; // If true we can run otherwise false means another instance is running.

Mutex mutex = new Mutex(false, // Should we be the owner no
                        "Jabberwocky", // Name of the mutex.
                        out NoInstanceCurrently); // Flag to tell us if it exists.

if (NoInstanceCurrently == true)
      Console.WriteLine("Press Enter to kill first instance");
      Console.WriteLine("Another Instance is Running");


  1. If you using a local Mutex variable, you should be sure to call GC.KeepAlive for that variable. The GC is free to release your mutex variable starting at if(NoInstanceCurrently == true) which means the mutex may be released while the application is running and you may not guard against more than one application instance running.

  2. Abhijeet Kulkarni says:

    That’s awesome. What an easy fix! Thanks for the post!

Leave a Reply