Using the Mutex construct
This recipe will describe how to synchronize two separate programs using the Mutex construct. A Mutex construct is a synchronization primitive that grants exclusive access of the shared resource to only one thread.
Getting ready
To step through this recipe, you will need Visual Studio 2015. There are no other prerequisites. The source code for this recipe can be found at BookSamples\Chapter2\Recipe2.
How to do it...
To understand the synchronization of two separate programs using the Mutex construct, perform the following steps:
- Start Visual Studio 2015. Create a new C# console application project.
- In the
Program.csfile, add the followingusingdirectives:using System; using System.Threading; using static System.Console;
- Inside the
Mainmethod, add the following code snippet:const string MutexName = "CSharpThreadingCookbook"; using (var m = new Mutex(false, MutexName)) { if (!m.WaitOne(TimeSpan.FromSeconds(5), false)) { WriteLine("Second instance...