- 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.
- Instant Testing with CasperJS
- AngularJS入門(mén)與進(jìn)階
- Delphi程序設(shè)計(jì)基礎(chǔ):教程、實(shí)驗(yàn)、習(xí)題
- 軟件界面交互設(shè)計(jì)基礎(chǔ)
- Python數(shù)據(jù)分析基礎(chǔ)
- Scratch 3.0少兒編程與邏輯思維訓(xùn)練
- Web全棧工程師的自我修養(yǎng)
- C語(yǔ)言程序設(shè)計(jì)
- 21天學(xué)通C++(第5版)
- Clojure for Machine Learning
- Learning Node.js for .NET Developers
- Advanced Python Programming
- C/C++代碼調(diào)試的藝術(shù)(第2版)
- Sitecore Cookbook for Developers
- 量子計(jì)算機(jī)編程:從入門(mén)到實(shí)踐