- 阅读权限
- 255
- 威望
- 1 级
- 论坛币
- 49655 个
- 通用积分
- 55.9937
- 学术水平
- 370 点
- 热心指数
- 273 点
- 信用等级
- 335 点
- 经验
- 57805 点
- 帖子
- 4005
- 精华
- 21
- 在线时间
- 582 小时
- 注册时间
- 2005-5-8
- 最后登录
- 2023-11-26
|
Using the ManualResetEventSlim construct
- How to do it...
- To understand the use of the ManualResetEventSlim construct, perform the following steps:
- 1. Start Visual Studio 2015. Create a new C# console application project.
- 2. In the Program.cs file, add the following using directives:
- using System;
- using System.Threading;
- using static System.Console;
- using static System.Threading.Thread;
- 3. Below the Main method, add the following code:
- static void TravelThroughGates(string threadName, int seconds)
- {
- WriteLine($"{threadName} falls to sleep");
- Sleep(TimeSpan.FromSeconds(seconds));
- WriteLine($"{threadName} waits for the gates to open!");
- _mainEvent.Wait();
- WriteLine($"{threadName} enters the gates!");
- }
- static ManualResetEventSlim _mainEvent = new
- ManualResetEventSlim(false);
- 4. Inside the Main method, add the following code:
- var t1 = new Thread(() => TravelThroughGates("Thread 1", 5));
- var t2 = new Thread(() => TravelThroughGates("Thread 2", 6));
- var t3 = new Thread(() => TravelThroughGates("Thread 3", 12));
- t1.Start();
- t2.Start();
- t3.Start();
- Sleep(TimeSpan.FromSeconds(6));
- WriteLine("The gates are now open!");
- _mainEvent.Set();
- Sleep(TimeSpan.FromSeconds(2));
- _mainEvent.Reset();
- WriteLine("The gates have been closed!");
- Sleep(TimeSpan.FromSeconds(10));
- WriteLine("The gates are now open for the second time!");
- _mainEvent.Set();
- Sleep(TimeSpan.FromSeconds(2));
- WriteLine("The gates have been closed!");
- _mainEvent.Reset();
- 5. Run the program.
复制代码
|
|