C # Multi-thread EventWaitHandle re-use

Source: Internet
Author: User

1     /// <summary>2     ///file transfer, used to obtain full-text files, automatically based on the number of full-text files, open a certain number of threads, using producer consumption mode3     /// </summary>4      Public classFiletranser5     {6         Private StaticIfiletranser Transer =NewRealfiletranser ();7         //file Queue8         StaticQueue<fulltextlistviewmodel> Filetaskqueue =NewQueue<fulltextlistviewmodel>();9         //To ensure thread safety, a lock is used to secure the access to the queueTen         ReadOnly Static ObjectLocker =New Object(); One         //Cheng signal to work line via AutoResetEvent A         StaticEventWaitHandle AutoResetEvent =NewAutoResetEvent (false); -          Public StaticCancellationTokenSource Cancel =NULL; -  the         Static intMaxthreadcount =5; -         Static intMinthreadcount =1; -         Static intPageSize = -; -  +         Staticlist<thread> threads =NewList<thread>(); -         Static BOOLIsRunning =false; +          Public Static voidStart (Fulltextlistviewmodel model,intTotal ) A         { at             if(Cancel! =NULL&& Cancel. iscancellationrequested)return; -             if(IsRunning = =false|| ThreadCount >threads. Count) -             { -                 intStartcount = ThreadCount-threads. Count; -IsRunning =true; -                 //task start, start worker thread in                  for(inti =0; i < Startcount; i++) -                 { toThread T =NewThread (work); +T.name ="f_"+ (i +1); -T.isbackground =false; the T.start (); * threads. ADD (t); $                 }Panax Notoginseng             } -             Lock(Locker) the             { + Filetaskqueue.enqueue (model); A             } the AutoResetEvent.Set (); +         } -          Public Static voidCancel () $         { $IsRunning =false; - threads. Clear (); -             if(Cancel! =NULL) the             { - Cancel. Cancel ();Wuyi             } the AutoResetEvent.Set (); -Logger.Log ("Cancel get full-text thread execution"); Wu         } -         /// <summary>Implementation Work</summary> About         Static voidWork () $         { -              while(true) -             { -                 if(Cancel. iscancellationrequested) A                 { +Logger.Log ("thread canceled, current thread:"+Thread.CurrentThread.Name); the AutoResetEvent.Set (); -                      Break; $                 } the                 Else the                 { theFulltextlistviewmodel model =NULL; the                     Lock(Locker) -                     { in                         if(Filetaskqueue.count >0) the                         { theModel =filetaskqueue.dequeue (); About                         } the                     } the                     if(Model! =NULL) the                     { +Logger.Log ("the full-text transfer file has started with the current ID:"+ model. Clienttaskid +", current thread:"+Thread.CurrentThread.Name); - FileTranser.Transer.DoWork (model); the                     }Bayi                     Else the                     { theLogger.Log ("Threads"+ Thread.CurrentThread.Name +", has been blocked, waiting for the task"); - Autoresetevent.waitone (); -                     } the                 } the             } the         } the}

This code of less than 100 lines, the idea is that the producer consumption pattern, which applied the AutoResetEvent, literally, is an automatic reset event, which is a subclass of EventWaitHandle.

Let's start by looking at the meaning of this code. Line 8th, defines a file transfer queue Filetaskqueue, which is used to receive producer-produced entities, which are objects of type Fulltextlistviewmodel. 29-35 lines, open a number of threads, 40 lines, to the queue locking (incoming team must be locked, because of multithreading), put the model into the queue, followed by the AutoResetEvent.Set () method, the release of the blocked thread. At this point, if there are three threads, there are only 1 model in the queue, then three threads consume a model, two threads are bound to be blocked, and the thread that gets the model is blocked until the next model enters the team, the three threads are like three athletes running to carry things, If things are done, just stand by and listen to the gun, when does the gun ring? If something comes, it will shoot. So three athletes make every effort to grab things, if one of them grabbed, then the other two people stand by, if you want to carry more things, then the three athletes have been busy, in accordance with the principle of first move, moved away.

According to the understanding just now, then AutoResetEvent, is just that gun, it has two states, one is the firing state (non-terminating state), the other is already open gun State (terminating state). If the gun has been fired, then when will the state change? I think it's supposed to be a shot. Autoresetevent.waitone () The blocked thread continues to run, and the state automatically turns into a firing state for the next shot. WaitOne is waiting for gunfire, otherwise it has been blocked. If more than one thread is blocking at this point, only one thread is released after the gunshot is heard. This is critical, otherwise there will be unexpected results when designing multithreaded programs.

C # Multi-thread EventWaitHandle re-use

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.