- Multithreading in C# 5.0 Cookbook
- Eugene Agafonov
- 317字
- 2021-07-21 18:10:01
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 { Console.WriteLine("Running!"); Console.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 was acquired, the program simply displays Running, and waits for any key to be pressed 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 executing. However, if we keep waiting for 5 seconds, the second copy of the program will fail to acquire the mutex.
This makes it possible to synchronize threads in different programs, which could be useful in a large number of scenarios.
- Delphi程序設(shè)計(jì)基礎(chǔ):教程、實(shí)驗(yàn)、習(xí)題
- 深入淺出Electron:原理、工程與實(shí)踐
- PostgreSQL Cookbook
- Git高手之路
- 征服RIA
- Python時(shí)間序列預(yù)測
- Spring Boot實(shí)戰(zhàn)
- 測試架構(gòu)師修煉之道:從測試工程師到測試架構(gòu)師
- UI設(shè)計(jì)基礎(chǔ)培訓(xùn)教程(全彩版)
- Visual C++從入門到精通(第2版)
- SAP Web Dynpro for ABAP開發(fā)技術(shù)詳解:基礎(chǔ)應(yīng)用
- Sitecore Cookbook for Developers
- VMware vSphere Design Essentials
- Learning TypeScript
- MATLAB計(jì)算機(jī)視覺實(shí)戰(zhàn)