C # ManualResetEvent Signal status determines whether the thread pool ends
This is an important piece of code, the two-hour study of Piglet, which is recorded for reference.
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading;namespaceend of thread pool conclusion synthesis demo {classProgram { Public Static intICount =0; Public Static intMaxCount =Ten;//allow up to 10 threads to run in a thread pool StaticManualResetEvent Eventx =NewManualResetEvent (false);//creates a new ManualResetEvent object and initializes it to a signal-free State Static voidMain (string[] args) {Console.WriteLine ("ManualResetEvent Initial signal-free status"); Console.WriteLine ("the thread pool has a maximum value of {0} threads. ", MaxCount); for(intIItem =1; IItem <= MaxCount; iitem++) { //inserting a queue elementConsole.WriteLine ("join thread {0}", IItem); ThreadPool.QueueUserWorkItem (NewWaitCallback (FUN1), (Object) IItem); } Console.WriteLine ("wait for the thread pool to complete the operation ... ");//waits for the event to complete, that is, the thread calls the Manualresetevent.set () methodEventx.waitone (Timeout.infinite,true);//the WaitOne () method causes the thread that calls it to wait until the Eventx.set () method is calledConsole.WriteLine ("thread pool ends! "); Console.ReadLine (); } Public Static voidFUN1 (Objectj) {Console.WriteLine ("{0} {1}:", Thread.CurrentThread.GetHashCode (), j.tostring ()); Thread.Sleep ( +); Interlocked.Increment (refiCount); if(ICount = =MaxCount) {Console.WriteLine (); Console.WriteLine ("set ManualResetEvent to signaled state, Setting Eventx"); Eventx.set (); } }}}
Whether C # multithreading ends can be judged by the thread pool