C # uses AutoResetEvent to implement sequential execution of threads

Source: Internet
Author: User

A few days ago a friend asked me how to implement the sequential execution of threads, really, although read the CLR this book, also the thread part of the reading two times, but this problem comes out after still not a train of thought. Today, when searching for information, I accidentally see AutoResetEvent again, of course, I know it is related to threads, used to handle thread switching and so on (may be wrong before the test demo), so decided to use AutoResetEvent to deal with the above problem.

Here in the park a friend of the example to illustrate, this example is to buy a book-"Payment-" take the book this process, the process will continue n (through variable settings) times, and each time to follow the order, there may be classmates doubt, directly sleep not good, why do not want multiple threads, If the process of processing a certain period of time is too long or the business is complex, then the entire program is not responding directly, so add multithreading here to ensure that the program response.

Class Program {//number of cycles const int numiterations = 10;        Buy book static AutoResetEvent buyresetevent = new AutoResetEvent (false);        Payment static AutoResetEvent payresetevent = new AutoResetEvent (false);       Fetch the book static AutoResetEvent getbookevent = new AutoResetEvent (false);        Number of cycles of static int numbers; The static void Main (string[] args) {//payment threads Thread Paymoneythread = new Thread (new ThreadStart (P            Aymoneyproc));            Paymoneythread.name = "Pay thread";            Fetch a book thread getbookthread = new Thread (new ThreadStart (Getbookproc));            Getbookthread.name = "Fetch the book thread";            Paymoneythread.start ();            Getbookthread.start ();                for (int i = 1; I <= numiterations; i++) {Console.WriteLine ("Buy book Thread: quantity {0}", i);                Number = i;                Allow the payment thread to wait for Payresetevent.set (); Prohibit buying a book thread waiting for BUYresetevent.waitone ();        } console.read (); } static void Paymoneyproc () {while (true) {//wait for payment pay                Resetevent.waitone ();                Console.WriteLine ("{0}: quantity {1}", Thread.CurrentThread.Name, number);            Allow the book thread to wait for Getbookevent.set ();                }} static void Getbookproc () {while (true) {//wait for payment                      Getbookevent.waitone ();                Console.WriteLine ("{0}: quantity {1}", Thread.CurrentThread.Name, number);                Console.WriteLine ("------------------------------------------");            Allow to buy the book thread to wait (to this step a complete book flow on the execution end, exactly in accordance with the book-"Payment-" the process of taking the book) Buyresetevent.set (); }        }    }

The code above is not complex, but there are several key objects and methods that are described in detail next.

1. Respectively define the purchase of books, payment, take book three AutoResetEvent, note the definition of the time passed false, which is also autoset default is not available, you need to manually call the Set method can do it. The object is the key to determining whether a request can be WaitOne, and when autoresetevent.set execution can use Autoresetevent.waitone to make a wait request, If there is another WaitOne request, continue to wait for set execution;

2. Look at the For loop first, in the loop we use payresetevent.set () This code, which also paythread in the WaitOne request can be approved (described below), and we added Buyresetevent.waitone ()(so that before the end of the last purchase process, the new process is not enforceable, which is our biggest problem, to ensure that the threads are executed in sequence);

3. The thread that defines the payment and the book is defined, and within the method is a while loop, which is primarily to allow the process to be carried out many times, after all the threads are executed only once. Of course this is not the point, the focus is the while in our operation, first look at the operation of Paythrea, first call Payresetevent.waitone () Request a wait operation, of course, can be executed immediately, because in 2 we said for is called the Payresetevent.set () operation, so that you can directly get a request response, output key information, and then to the point, we call the Getbookevent.set (), which is why, Because the payment is not successful can not take the book, Ah, that is stealing. Attention, attention, attention, important words three times , the getbookthread operation also has a WaitOne request, but why not execute it, because there is no set it, When we initialize the AutoResetEvent we set the false, so the default is not to get a request, you have to call Set manually, because in Paymoneythread's last line of code we call the Getbookevent.set () , so that the Getbookevent.waitone is available. In the Getbookthread in turn the key information, the last line of code came again, again called a autoresetevent.set (), yes is the object of buying books, because to this step to complete the book flow is over, you can buy a book Ah ah ah ah ah, can buy books , very happy AH. Then return to the last line of code in the For loop again, and buyresetevent.wait () is now resurrected, starting the first few times to buy the book flow.

Run as follows (absolutely true, without PS):

OK, back to the DPRK, something another day to discuss again.

C # uses AutoResetEvent to implement sequential execution of threads

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.