[Tips]: multithreading manualresetevent

Source: Internet
Author: User

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:

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.