C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
New: If the Mutex does not exist, it creates a new one. Further instances of the program then can tell that an instance is already open.
Exception: The program incurs one exception in the common case of the first instance being run. Exceptions are slower than many constructs.
But: If your program is computationally-intensive, it is more beneficial to avoid extra instances.
Note: The OpenExisting examples on Microsoft Docs also use exception handling. This is the recommended style.
Mutex.OpenExisting: Microsoft DocsC# program that uses Mutex and OpenExisting
using System;
using System.Threading;
class Program
{
static Mutex _m;
static bool IsSingleInstance()
{
try
{
// Try to open existing mutex.
Mutex.OpenExisting("PERL");
}
catch
{
// If exception occurred, there is no such mutex.
Program._m = new Mutex(true, "PERL");
// Only one instance.
return true;
}
// More than one instance.
return false;
}
static void Main()
{
if (!Program.IsSingleInstance())
{
Console.WriteLine("More than one instance"); // Exit program.
}
else
{
Console.WriteLine("One instance"); // Continue with program.
}
// Stay open.
Console.ReadLine();
}
}
Output
1. First execution will display "One instance"
2. Second execution will display "More than one instance"
3. Third execution is the same as second.
And: This behavior can be used to enforce synchronization between processes and threads.