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:
- Constructor for ManualResetEvent: Initializes a ManualResetEvent instance, allowing the initial state to be specified.
ManualResetEvent resetEvent = new ManualResetEvent(false); // 初始化为未终止状态
- Set() method: Set the ManualResetEvent to the signaled state, allowing waiting threads to continue execution.
resetEvent.Set();
- Reset() method: Sets the ManualResetEvent to a non-signaled state, blocking the waiting threads from continuing execution.
resetEvent.Reset();
- WaitOne() method: Blocks the current thread until a signal is received.
resetEvent.WaitOne();
- 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.