- Multithreading with C# Cookbook(Second Edition)
- Eugene Agafonov
- 324字
- 2021-07-09 19:35:37
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.cs
file, add the followingusing
directives:using System; using System.Threading; using static System.Console;
- 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)) { WriteLine("Second instance is running!"); } else { WriteLine("Running!"); ReadLine(); m.ReleaseMutex(); } }
- Run the program.
How it works...
When the main program starts, it defines a mutex with a specific name, providing the initialOwner
flag as false
. This allows the program to acquire a mutex if it is already created. Then, if no mutex is acquired, the program simply displays Running and waits for any key to be pressed in order to release the mutex and exit.
If we start a second copy of the program, it will wait for 5 seconds, trying to acquire the mutex. If we press any key in the first copy of a program, the second one will start the execution. However, if we keep waiting for 5 seconds, the second copy of the program will fail to acquire the mutex.
Tip
Note that a mutex is a global operating system object! Always close the mutex properly; the best choice is to wrap a mutex object into a using
block.
This makes it possible to synchronize threads in different programs, which could be useful in a large number of scenarios.
- Learning Microsoft Windows Server 2012 Dynamic Access Control
- JavaScript百煉成仙
- 國際大學生程序設計競賽中山大學內部選拔真題解(二)
- Learning ROS for Robotics Programming(Second Edition)
- 機器學習系統:設計和實現
- Java異步編程實戰
- 跟老齊學Python:輕松入門
- 零基礎學Java(第4版)
- PHP+MySQL+Dreamweaver動態網站開發實例教程
- Mastering Data Mining with Python:Find patterns hidden in your data
- Hands-On Full Stack Development with Spring Boot 2.0 and React
- 響應式Web設計:HTML5和CSS3實戰(第2版)
- Visual Basic 6.0程序設計實驗教程
- 快速入門與進階:Creo 4·0全實例精講
- INSTANT Apache ServiceMix How-to