Using the Mutex construct
This recipe will describe how to synchronize two separate programs using a Mutex
construct. Mutex
is a primitive synchronization that grants exclusive access of the shared resource to only one thread.
Getting ready
To step through this recipe, you will need Visual Studio 2012. There are no other prerequisites. The source code for this recipe could be found at 7644_Code\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 2012. Create a new C# Console Application project.
- In the
Program.cs
file, add the followingusing
directives:using System; using System.Threading;
- Inside the
Main
method, add the following code snippet:const string MutexName = "CSharpThreadingCookbook"; using (var m = new Mutex(false, MutexName)) { if (!m.WaitOne(TimeSpan.FromSeconds(5), false)) { Console.WriteLine("Second instance is running!"); } else...