The problem solved:
1. When you need to get the results of a multithreaded execution method
2. How to get the main thread, wait for all the sub-threads to end directly
classProgram {Static voidMain (string[] args) {IList<ManualResetEvent> listmanual =NewList<manualresetevent>(); List<ThreadReturnData> testlist =NewList<threadreturndata>(); for(inti =0; I <Ten; i++) {Threadreturndata temp=NewThreadreturndata (); Temp.manual=NewManualResetEvent (false); Temp.parm="Test"; Listmanual.add (temp.manual); Testlist.add (temp); ThreadPool.QueueUserWorkItem (NewWaitCallback (temp. Returnthreaddata), i); } //wait for this query thread to complete execution if(Listmanual.count >0) {WaitHandle.WaitAll (Listmanual.toarray ()); } foreach(varIteminchtestlist) {Console.WriteLine (Item.result); //The result of the asynchronous } } Public classThreadreturndata { PublicManualResetEvent Manual; Public stringParm; Public stringresult; Public voidReturnthreaddata (Objectinfo) {Result= Parm +info. ToString (); Manual. Set (); } }
There are two ways to pass parameters to the method that a child thread needs to execute, such as the "I" above for the method, and another way to set a property (Parm) for the instance of the Returnthreaddata method in which the child thread needs to execute. When you need to execute a method money assigns a value to the property (Temp.parm = "Test"), the property of this instance can be called directly in the method. How or what is the result of a sub-thread execution, the principle is the same as the second way of assigning values to the parameter, setting a result attribute (result) in the class Threadreturndata of the method, and assigning the result directly to result after the method is executed. The result of execution can be obtained in the temp instance of the main thread. So why do both the main thread and the child thread have access to the temp instance, and the temp instance is created in the main thread, passing the returnthreaddata of the temp instance to the WaitCallback delegate that the child thread needs to execute. At the same time, the instance of the Returnthreaddata instance method is also passed to the delegate (with an implied this parameter is the temp instance), so you can directly refer to the property of the instance where the method is executed when executing the delegate method. It is essentially the passing of a reference type, as long as the reference type's data is changed somewhere in the reference, so the other references to the reference type can be obtained in this change.
Use multi-Threading to execute a method with a return value