Run only one instance of a program in C#

This example shows you how to ensure that only one instance of an application is running.

// Ensure only one instance of this application is running.
bool alone = false;
Mutex m = new Mutex(true, "<name>", out alone);
 
if (!alone)
{
    Console.WriteLine("Another instance is already running.");
    Console.ReadKey();
    return;
}
 
Console.WriteLine("Running...\n");
Console.ReadKey();
 
// Needed to ensure only one instance is running.
GC.KeepAlive(m);

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">