We used multithreading, basically with thread, if the client can also use the BackgroundWorker component to perform some operations in the background, this article mainly explains the TaskFactory method
//Create a parameter helper class that can pass multiple parameters classFunpara { Public intNumber ; Public stringName; } //create multi-threaded methods with return values Public Staticlist<string>GetNumber (Funpara fp) {List<string> list =Newlist<string>(); for(inti =0; I < +; i++) { stringstr =string. Format ("{0}_{1}", i +Fp.number, FP. Name); List. ADD (str); Console.WriteLine (str); } returnlist; } TaskFactory TaskFactory=NewTaskFactory (); //an array that can have a return value asynchronous operationlist<task<list<string>>> tasks =Newlist<task<list<string>>>(); //create a delegate with a return valuefunc<Object, list<string>> action = (ObjectARG) = ={Funpara arg0= arg asFunpara; returnGetNumber (arg0); }; //This method creates and starts a task, and this example uses 3 threads for(inti =0; I <3; i++) {Funpara FUNP=NewFunpara (); Funp.number= i +1; if(i = =0) {FUNP. Name="Bob"; } Else if(i = =1) {FUNP. Name="John"; } Else{FUNP. Name="Kake"; } tasks. ADD (Taskfactory.startnew (Action, FUNP)); } //use a task to perform a receive return valueTask taskList =NULL; List<string> Listall =Newlist<string>(); ObjectLockObject =New Object(); if(Tasks.) Count >0) { //creates a continuation task that starts when a set of specified tasks have completed.TaskList = task.factory.continuewhenall<list<string>> (tasks. ToArray (), completedtasks = { foreach(task<list<string>> Iteminchcompletedtasks) {List<string> list =item. Result; Lock(lockobject) {Listall.addrange (list. ToArray ()); } } }); } //wait for all threads to finish executingtasklist.wait (); //Output Results foreach(stringStrinchListall) {Console.WriteLine (str); }
The above method has basically solved the problem of parallel and receiving asynchronous return value, which is very useful for beginners, in addition, because some exceptions are difficult to capture, the thread starts before running this section
Taskscheduler.unobservedtaskexception + = (object sender, Unobservedtaskexceptioneventargs EventArgs) = { eventargs.setobserved (); = = {Console.WriteLine ("exception:{0}", ex. Message); return true ; }); };
Well, here it is, this is a complete, parallel example with the receive return value, mark, for ease of use.
Parallel Simple Example