第一、简单介绍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();}}}
}}
运行测试结果
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。
您可能感兴趣的文章:C#中多线程ManualResetEvent 与 AutoResetEvent 区别C# AutoResetEvent的具体使用方法C#中AutoResetEvent控制线程用法小结C#多线程之线程通讯(AutoResetEvent) C#使用AutoResetEvent实现同步C# ManualResetEvent用法详解C# ManualResetEvent使用方法详解C# AutoResetEvent和ManualResetEvent的实现示例
