这篇文章主要为大家详细介绍了C#中ManualResetEvent用法,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
这篇文章主要为大家详细介绍了C#中ManualResetEvent用法,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
这篇文章主要为大家详细介绍了C#中ManualResetEvent用法,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
第一、简单介绍
manualresetevent 允许线程通过发信号互相通信。通常,此通信涉及一个线程在其他线程进行之前必须完成的任务。当一个线程开始一个活动(此活动必须完成后,其他线程才能开始)时,它调用 reset 以将 manualresetevent 置于非终止状态,此线程可被视为控制 manualresetevent。调用 manualresetevent 上的 waitone 的线程将阻止,并等待信号。
当控制线程完成活动时,它调用 set 以发出等待线程可以继续进行的信号。并释放所有等待线程。一旦它被终止,manualresetevent 将保持终止状态(即对 waitone 的调用的线程将立即返回,并不阻塞),直到它被手动重置。可以通过将布尔值传递给构造函数来控制 manualresetevent 的初始状态,
如果初始状态处于终止状态,为 true;否则为 false。

第二、代码演示
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
|
using system;using system.collections.generic;using system.linq;using system.text;using system.threading;using system.threading.tasks; namespace consoleapplication2{ class mythread { thread t = null; manualresetevent manualevent = new manualresetevent(true);//为trur,一开始就可以执行 private void run() { while (true) { this.manualevent.waitone(); console.writeline("线程id:{0}", thread.currentthread.managedthreadid); thread.sleep(2000); } } public void start() { this.manualevent.set(); } public void stop() { this.manualevent.reset(); } public mythread() { t = new thread(this.run); t.start(); } } class program { static void main(string[] args) { mythread myt = new mythread(); while (true) { console.writeline("输入 stop 后台线程挂起 start 开始执行!"); string str = console.readline(); if (str.tolower().trim() == "stop") { console.writeline("线程停止运行...\n"); myt.stop(); } if (str.tolower().trim() == "start") { console.writeline("线程开启运行...\n"); myt.start(); } } } }} |
运行测试结果

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持米米素材网。
发表评论