Mutex
The C# Mutex
type ensures blocks of code are executed only once at a time. It can create named mutexes that can be opened by other processes.
With the Mutex
type, we ensure only one instance is run on the computer. This type provides the WaitOne
, WaitAll
and WaitAny
methods.
Here we use Mutex.OpenExisting
. If this method throws an exception, the specified named Mutex
does not exist or is inaccessible. The IsSingleInstance
method uses this behavior.
Mutex
does not exist, it creates a new one. Further instances of the program then can tell that an instance is already open.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(); } }1. First execution will display "One instance" 2. Second execution will display "More than one instance" 3. Third execution is the same as second.
We can call Release on a Mutex
instance once we are done with it. In the example this is not necessary—the Mutex
will be released when the program exits.
WaitOne
method blocks the current thread until the Mutex
has been released.Release()
method to release the Mutex
. This can help reduce problems with locking.The Mutex
type provides a way to use system-wide synchronization. It can also synchronize threads within a single program.
When a Mutex
has a string
name, it can be opened from other processes with OpenExisting
. This behavior can be used to enforce synchronization between processes and threads.