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();
                }
            }
        }
        
    }
}

 运行测试结果

 

posted @   lance2008  阅读(807)  评论(0编辑  收藏  举报
努力加载评论中...
点击右上角即可分享
微信分享提示