Sometimes we create multiple threads, and we need to know if we have all done our job. For example, how to start a multi-threaded download, how to terminate all threads, and then continue the program exit after making sure all the threads are terminated?
1 Public Partial classMainwindow:window2 {3 PublicMainWindow ()4 {5 InitializeComponent ();6 }7 8 Private volatile BOOLIscontinue =false;9 StaticList<waithandle> waithandles =NewList<waithandle>();Ten One Private voidButton_threadstart_click (Objectsender, RoutedEventArgs e) A { - if(iscontinue) - return; the -Iscontinue =true; - -Thread T =NewThread (testwaitall);//Open a thread first +T.name ="Testwaitall"; - T.start (); + } A at Private voidButton_threadstop_click (Objectsender, RoutedEventArgs e) - { -Iscontinue =false; - } - - Public voidTestwaitall () in { - for(inti =0; I <5; i++) to {
WaitHandle is a type of extraction category so it has to manifest its subclass, that is, the ManualResetEvent class or the AutoResetEvent class +ManualResetEvent WH =NewManualResetEvent (false); - Waithandles.add (WH); the ThreadPool.QueueUserWorkItem (Task, WH); * } $ WaitHandle.WaitAll (Waithandles.toarray ());Panax Notoginseng -Console.WriteLine ("All threads are terminated!!!!!! "); theMessageBox.Show ("It's done! "); + } A the Public voidTask (Object State) + { -ManualResetEvent MRE =(ManualResetEvent) state; $ while(iscontinue) $ { -Console.WriteLine ("{0}: {1}", MRe. Handle.tostring (), DateTime.Now.ToLongTimeString ()); -Thread.Sleep ( +); the } -Console.WriteLine ("Current thread Termination");Wuyi MRE. Set (); the } -}
If you do not turn on the thread but call Testwaitall () directly on the UI thread, there will be an exception
WaitHandle.WaitAll (Waithandles), the main thread waits for all threads to complete the work
WaitHandle.WaitAll (waithandles,2000), set the wait time, indicating that the main thread is willing to wait for the child thread to execute for two seconds
WaitHandle.WaitAny is waiting for any thread to finish the job.
Reference:
Thread executes the sequence of loops to start the WaitHandle.WaitAll method
C # Multi-thread two: ManualResetEvent and AutoResetEvent
C # multithreaded learning thread pool [ThreadPool]
C # Multi-Threading automatic management (thread pool)
C # WaitHandle: Managing multithreaded States