(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");