C# Using a named Mutex to ensure that a single instance of a program runs at a time
By Indranil Chatterjee
This FAQ illustrates the usafe of named Mutex to ure that a single instance of a program runs at a time.
class Program
{
static void Main(string[] args)
{
using (var mutex = new Mutex(false, "WordCountProgram"))
{
// Wait a few seconds if contended, in case another instance
// of the program is still in the
process of shutting down.
if (!mutex.WaitOne(TimeSpan.FromSeconds(3), false))
{
Console.WriteLine("Another app instance is running. Bye!");
return;
}
RunProgram();
}
}
private static void RunProgram()
{
Console.WriteLine("Running. Press Enter to exit");
Console.ReadLine();
}
}
//Try running two instances of the executable for this program. Only one of them
will be allowedto execute at a time.
C# Using a named Mutex to ensure that a single instance of a program runs at a time (1895 Views)