This paper is to consolidate the foundation
AutoResetEvent
Concept: Notifies the waiting thread that an event has occurred
If AutoResetEvent is a non-terminating state, the thread is blocked and waits for the current control resource's thread to notify the resource that it is available by calling Set. Call set to signal AutoResetEvent to release the waiting thread.
The event status can be set through the constructor false to non-terminating, true to terminating
Common methods:
Set (); Sets the event state to the signaled state, allowing one or more waiting threads to continue.
Reset (); Set the event state to a non-terminating state, causing the thread to block
WaitOne (); Blocks the current thread until the current WaitHandle received a signal.
ManualResetEvent usage is similar, there is a little difference, can be seen below
Here's a simple example to illustrate this basic usage
classProgram {//Set event status to non-terminating Private StaticManualResetEvent _manualresetevent=NewManualResetEvent (false); Private StaticThread _thread =NewThread (NewThreadStart (Threadmethod)); Private Static int_count =0; Static voidMain (string[] args) {_thread. Start (); Console.ReadLine (); _manualresetevent.set ();//notifies the waiting thread to continue } Private Static voidThreadmethod () { while(true) {_manualresetevent.waitone ();//The following statement will not execute because the event status above is set to non-terminating, unless you receive a signal to continueThread.Sleep ( +); Console.WriteLine (_count++); } }
There will be no output at first, and the thread will not continue until you enter the data.
The results are as follows
W
0
1
2
3
4
5
6
7
8
...
Note here antoresetevent in the WaitOne method will switch the signal (not professional, understand good), that is, this time to receive a signal, the next time will become no signal, and then carry out a signal, so reciprocating
Here is the antoresetevent implementation
classProgram {//Set event status to non-terminating Private StaticAutoResetEvent _autoresetevent=NewAutoResetEvent (false); Private StaticThread _thread =NewThread (NewThreadStart (Threadmethod)); Private Static int_count =0; Static voidMain (string[] args) {_thread. Start (); Console.ReadLine (); _autoresetevent.set (); } Private Static voidThreadmethod () { while(true) {_autoresetevent.waitone ();//The following statement will not execute because the event status above is set to non-terminating, unless you receive a signal to continueThread.Sleep ( +); Console.WriteLine (_count++); _autoresetevent.set ();//The above WaitOne becomes no signal after execution, so that the next loop is blocked, this step can make the next loop to receive the continuation of the signal} }}
AutoResetEvent and ManualResetEvent