当前位置: 移动技术网 > IT编程>开发语言>c# > C#中ManualResetEvent用法详解

C#中ManualResetEvent用法详解

2019年07月18日  | 移动技术网IT编程  | 我要评论

第一、简单介绍

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

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

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

第二、代码演示

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


运行测试结果

 以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网