How to use ManualResetEvent in C#?

In C#, ManualResetEvent is a synchronization primitive that allows one thread to notify another thread that an event has occurred. It primarily consists of the following methods:

  1. Constructor for ManualResetEvent: Initializes a ManualResetEvent instance, allowing the initial state to be specified.
ManualResetEvent resetEvent = new ManualResetEvent(false); // 初始化为未终止状态
  1. Set() method: Set the ManualResetEvent to the signaled state, allowing waiting threads to continue execution.
resetEvent.Set();
  1. Reset() method: Sets the ManualResetEvent to a non-signaled state, blocking the waiting threads from continuing execution.
resetEvent.Reset();
  1. WaitOne() method: Blocks the current thread until a signal is received.
resetEvent.WaitOne();
  1. WaitOne(timeout) method: blocks the current thread until a signal is received or a timeout occurs.
resetEvent.WaitOne(1000); // 等待1秒钟

Using ManualResetEvent makes it easy to achieve thread synchronization and communication, such as coordinating the execution order of threads in a multi-threaded environment.

Leave a Reply 0

Your email address will not be published. Required fields are marked *