ManualResetEvent 类的用法

引用:http://jingyan.baidu.com/article/0eb457e50949d203f1a9050f.html

先说是一下  ManualResetEvent 是一线程用来控制别一个线程的信号。大家可以把它看成 操作系统原理中说到的pv操作如下图所说是 ManualResetEvent 对象起一个信使的作用。

 

ManualResetEvent 对象的两个控制方法。

1、this.manualEvent.Reset(); //将事件状态设置为非终止状态,导致线程阻止。

2、this.manualEvent.Set();   //将事件状态设置为终止状态,允许一个或多个等待线程继续。

说了这么多光说不做还真没有用,接下来看代码!

 1 public class MyThread
 2 {
 3     Thread t = null;
 4     ManualResetEvent manualEvent = new ManualResetEvent(true);//为trur,一开始就可以执行
 5 
 6     private void Run()
 7     {
 8         while (true)
 9         {
10             this.manualEvent.WaitOne();
11             Console.WriteLine("Thread Id:{0},Name:{1}.", Thread.CurrentThread.ManagedThreadId,Thread.CurrentThread.Name);
12             Thread.Sleep(1000);
13         }
14     }
15 
16     public void Start()
17     {
18         this.manualEvent.Set();
19     }
20 
21     public void Stop()
22     {
23         this.manualEvent.Reset();
24     }
25 
26     public MyThread(string threadName="thread001")
27     {
28         t = new Thread(this.Run);
29         t.Name = threadName;
30         t.Start();
31     }
32 
33 } 
View Code

调用方法:

 1 class Program
 2 {
 3     static void Main(string[] args)
 4     {
 5         MyThread myt = new MyThread("MyThread001");
 6 
 7         while (true)
 8         {
 9             Console.WriteLine("输入 stop后台线程挂起 start 开始执行!");
10             string str = Console.ReadLine();
11             if (str.ToLower().Trim() == "stop")
12             {
13                 myt.Stop();
14             }
15 
16             if (str.ToLower().Trim() == "start")
17             {
18                 myt.Start();
19             }
20         }
21     }
22 }
View Code

调用流程:

 

posted @ 2015-06-28 11:28  升级者  阅读(219)  评论(0编辑  收藏  举报