- Multithreading with C# Cookbook(Second Edition)
- Eugene Agafonov
- 281字
- 2021-07-09 19:35:38
Using the CountDownEvent construct
This recipe will describe how to use the CountdownEvent
signaling construct to wait until a certain number of operations complete.
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\Recipe6
.
How to do it...
To understand the use of the CountDownEvent
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; using static System.Threading.Thread;
- Below the
Main
method, add the following code:static CountdownEvent _countdown = new CountdownEvent(2); static void PerformOperation(string message, int seconds) { Sleep(TimeSpan.FromSeconds(seconds)); WriteLine(message); _countdown.Signal(); }
- Inside the
Main
method, add the following code:WriteLine("Starting two operations"); var t1 = new Thread(() => PerformOperation("Operation 1 is completed", 4)); var t2 = new Thread(() => PerformOperation("Operation 2 is completed", 8)); t1.Start(); t2.Start(); _countdown.Wait(); WriteLine("Both operations have been completed."); _countdown.Dispose();
- Run the program.
How it works...
When the main program starts, we create a new CountdownEvent
instance, specifying that we want it to signal when two operations complete in its constructor. Then, we start two threads that signal to the event when they are complete. As soon as the second thread is complete, the main thread returns from waiting on CountdownEvent
and proceeds further. Using this construct, it is very convenient to wait for multiple asynchronous operations to complete.
However, there is a significant disadvantage; _countdown.Wait()
will wait forever if we fail to call _countdown.Signal()
the required number of times. Make sure that all your threads complete with the Signal
method call when using CountdownEvent
.
- TypeScript入門與實戰(zhàn)
- Python從小白到大牛
- 編程卓越之道(卷3):軟件工程化
- 三維圖形化C++趣味編程
- AngularJS深度剖析與最佳實踐
- Practical DevOps
- PHP+MySQL網(wǎng)站開發(fā)項目式教程
- 微信小程序全棧開發(fā)技術(shù)與實戰(zhàn)(微課版)
- 劍指大數(shù)據(jù):企業(yè)級數(shù)據(jù)倉庫項目實戰(zhàn)(在線教育版)
- Unity&VR游戲美術(shù)設(shè)計實戰(zhàn)
- Training Systems Using Python Statistical Modeling
- Oracle Data Guard 11gR2 Administration Beginner's Guide
- Learning Kotlin by building Android Applications
- Kotlin進階實戰(zhàn)
- R語言實戰(zhàn)(第2版)