- 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.
- Advanced Quantitative Finance with C++
- 零基礎(chǔ)搭建量化投資系統(tǒng):以Python為工具
- C語(yǔ)言程序設(shè)計(jì)實(shí)訓(xùn)教程
- Clojure for Domain:specific Languages
- x86匯編語(yǔ)言:從實(shí)模式到保護(hù)模式(第2版)
- Nginx Lua開(kāi)發(fā)實(shí)戰(zhàn)
- Keras深度學(xué)習(xí)實(shí)戰(zhàn)
- C專家編程
- GameMaker Essentials
- Instant Debian:Build a Web Server
- Angular應(yīng)用程序開(kāi)發(fā)指南
- .NET 4.0面向?qū)ο缶幊搪劊簯?yīng)用篇
- AutoCAD基礎(chǔ)教程
- CryENGINE Game Programming with C++,C#,and Lua
- C語(yǔ)言王者歸來(lái)