服务器之家

服务器之家 > 正文

C#中ManualResetEvent用法详解

时间:2022-01-06 13:07     来源/作者:lance2008

第一、简单介绍

    manualresetevent 允许线程通过发信号互相通信。通常,此通信涉及一个线程在其他线程进行之前必须完成的任务。当一个线程开始一个活动(此活动必须完成后,其他线程才能开始)时,它调用 reset 以将 manualresetevent 置于非终止状态,此线程可被视为控制 manualresetevent。调用 manualresetevent 上的 waitone 的线程将阻止,并等待信号。

当控制线程完成活动时,它调用 set 以发出等待线程可以继续进行的信号。并释放所有等待线程。一旦它被终止,manualresetevent 将保持终止状态(即对 waitone 的调用的线程将立即返回,并不阻塞),直到它被手动重置。可以通过将布尔值传递给构造函数来控制 manualresetevent 的初始状态,

如果初始状态处于终止状态,为 true;否则为 false。

C#中ManualResetEvent用法详解

第二、代码演示

 

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

运行测试结果

C#中ManualResetEvent用法详解

 以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

标签:

相关文章

热门资讯

蜘蛛侠3英雄无归3正片免费播放 蜘蛛侠3在线观看免费高清完整
蜘蛛侠3英雄无归3正片免费播放 蜘蛛侠3在线观看免费高清完整 2021-08-24
yue是什么意思 网络流行语yue了是什么梗
yue是什么意思 网络流行语yue了是什么梗 2020-10-11
背刺什么意思 网络词语背刺是什么梗
背刺什么意思 网络词语背刺是什么梗 2020-05-22
2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全
2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全 2019-12-26
2021年耽改剧名单 2021要播出的59部耽改剧列表
2021年耽改剧名单 2021要播出的59部耽改剧列表 2021-03-05
返回顶部