Waithandle is used for exclusive access to shared resources. Both autoresetevent and manualresetevent inherit from it. The waithandle. waitone method will block the current thread until waithandle receives the signal. However, sometimes we need to test the waithandle status in a non-blocking way.
Public Virtual bool waitone (INT millisecondstimeout)
You can specify the waiting interval. True if the current instance receives a signal; otherwise, false. In particular, if millisecondstimeout is zero, this method will not be blocked. This method tests the status of the pending handle and returns immediately.
Manualresetevent Mre = new manualresetevent (false) // No signal by default
Mre. Set () allows the current instance to receive signals
Now let's firstProgramOutput Hello world every 10 seconds, which can be written as follows:
1: UsingSystem;
2: UsingSystem. Collections. Generic;
3: UsingSystem. LINQ;
4: UsingSystem. text;
5: UsingSystem. Threading;
6:
7: NamespaceMultithread
8:{
9:Public ClassProgram
10:{
11: static manualresetevent Mre = New manualresetevent ( false );
12:Static VoidMain ()
13:{
14: thread t = New thread ( New threadstart (Hello);
15:T. Start ();
16:While(True)
17:{
18:CharA = console. readkey (). keychar;
19:If(A. tostring (). toupper () ="X")
20:{
21:Mre. Set ();
22:T. Abort ();
23:T. Join ();
24:Console. writeline (T. Name +"STOPPED");
25:Break;
26:}
27:}
28:}
29:
30:Static VoidHello ()
31:{
32:While(True)
33:{
34:If(Mre. waitone (1*1000 ))Break;
35:Console. writeline ("Hello");
36:}
37:}
38:}
39:}
40: