ManualResetEvent 允许线程通过发信号互相通信。通常,此通信涉及一个线程在其他线程进行之前必须完成的任务。

public static ManualResetEvent mre = new ManualResetEvent(false);
ManualResetEvent建立时是把false作为start的初始状态,这个类用于通知另一个线程,让它等待一个或多个线程。注意,为了通知或监听同一个线程,所有的其它线程都能访问那个类。
等待线程这样写:
  mre.WaitOne();
这将引起等待线程无限期的阻塞并等待类来通知。
发信号的线程应该这样:
  mre.Set();
这样类就会被通知,值变成true,等待线程就会停止等待。在通知事件发生后,我们就可以使用下面语句把线程置于非终止状态,导致线程阻止:
  mre.Reset();
一个测试的例子:

ManualResetEvent用法using System;
ManualResetEvent用法
using System.Threading;
ManualResetEvent用法
namespace ThreadingTester
}

运行的结果为:
thread: waiting for an event
Main:0
Main:1
Main:2
Main:3
Main:4
Main:5
thread: got an event
Main:6
Main:7
Main:8
thread1: 0
Main:9
thread1: 1
Main: waiting for thread to stop
thread1: 2
Main: waiting for thread to stop
thread1: 3
Main: waiting for thread to stop
thread1: 4
Main: waiting for thread to stop
thread1: 5
Main: waiting for thread to stop
thread1: 6
Main: waiting for thread to stop
thread1: 7
Main: waiting for thread to stop
thread1: 8
Main: waiting for thread to stop
thread1: 9
Main: waiting for thread to stop

相关文章:

  • 2021-08-18
  • 2021-08-18
  • 2021-10-27
  • 2022-12-23
  • 2022-12-23
  • 2021-07-12
猜你喜欢
  • 2021-04-30
  • 2021-10-29
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案