C# ManualResetEvent 类的用法
来源:互联网 发布:程序员回老家能干嘛 编辑:程序博客网 时间:2024/05/05 17:51
先说是一下 ManualResetEvent 是一线程用来控制别一个线程的信号。大家可以把它看成 操作系统原理中说到的pv操作
如下图所说是 ManualResetEvent 对象起一个信使的作用。
ManualResetEvent 对象的两个控制方法。
1、this.manualEvent.Reset(); //将事件状态设置为非终止状态,导致线程阻止。
2、this.manualEvent.Set(); //将事件状态设置为终止状态,允许一个或多个等待线程继续。
说了这么多光说不做还真没有用,接下来看代码!
class MyThread { Thread t = null; ManualResetEvent manualEvent = new ManualResetEvent(true);//为trur,一开始就可以执行 private void Run() { while (true) { this.manualEvent.WaitOne(); Console.WriteLine("这里是 {0}", Thread.CurrentThread.ManagedThreadId); Thread.Sleep(5000); } } public void Start() { this.manualEvent.Set(); } public void Stop() { this.manualEvent.Reset(); } public MyThread() { t = new Thread(this.Run); t.Start(); } }
在 main 方法中要用到上面的类
static void Main(string[] args) { MyThread myt = new MyThread(); while (true) { Console.WriteLine("输入 stop后台线程挂起 start 开始执行!"); string str = Console.ReadLine(); if (str.ToLower().Trim() == "stop") { myt.Stop(); } if (str.ToLower().Trim() == "start") { myt.Start(); } } }
原理就说完了我们来看一下程序运行的结果!
文章转载自C# ManualResetEvent 类的用法,感谢作者 蒋乐兴 提供好文章
0 0
- C# ManualResetEvent 类的用法
- ManualResetEvent类的用法
- C#的ManualResetEvent在多线程中的用法
- C# ManualResetEvent 类的用法——如何控制子线程的暂停与继续
- C#中的线程与同步 ManualResetEvent用法
- 线程同步- EventWaitHandle类的子类ManualResetEvent的用法
- ManualResetEvent用法
- ManualResetEvent用法
- ManualResetEvent用法
- 【CSharp 学习笔记】关于ManualResetEvent的用法
- C#信号同步类型AutoResetEvent , ManualResetEvent用法和区别
- AutoResetEvent和ManualResetEvent用法
- C# ManualResetEvent使用测试
- 关于C#中AutoResetEvent和ManualResetEvent的一点学习心得
- C# 线程的挂起与唤醒 (AutoResetEvent,ManualResetEvent)
- C# 多线程 AutoResetEvent和ManualResetEvent
- ManualResetEvent的使用
- ManualResetEvent的使用
- Ubuntu 卡住了怎么办
- fedora/centos下gcc编译出现gcc: error trying to exec ‘cc1plus’: execvp: No such file or directory
- error C2440
- int main(int argc,char *argv[])
- java实现单链表,巩固基础
- C# ManualResetEvent 类的用法
- 九度oj 1099
- 重装Ubuntu系统后如何设定root密码
- 图片上传后回显,支持多张图片上传
- freemarker ftl常用语法
- android-UI组件实例大全(七)------Adapter类One之ListView
- Android 获取麦克风的音量(分贝)
- 架构设计中的6种常见安全误区
- iOS 短信与电话事件的获取