Home
Map
Mutex ExampleUse the Mutex type from System.Threading to synchronize between threads and processes.
C#
This page was last reviewed on May 4, 2023.
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.
Example. 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.
bool
Start 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.
Info 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.
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.
Discussion. 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.
Info The WaitOne method blocks the current thread until the Mutex has been released.
And We can call the Release() method to release the Mutex. This can help reduce problems with locking.
A summary. 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.
Process
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on May 4, 2023 (edit).
Home
Changes
© 2007-2023 Sam Allen.