Share three columns of a Task and three columns of a Task.
This time I want to share several columns of the C # Task. I feel that the most practical method is the encapsulated paging Task execution method. This method is also commonly used to execute multiple tasks in my work, I don't know whether you can use this function. Let's get started.
1. Sequential task execution
1 // execute two tasks in sequence. factory. startNew <int> () => {Console. writeLine (1); return 1 ;}). 3 // wait for 5 seconds before outputting 2, 3, 4 ContinueWith (task) => 5 {6 7 Stopwatch wt = new Stopwatch (); 8 wt. start (); 9 Thread. sleep (1000*5); 10 wt. stop (); 11 Console. writeLine ("waiting: {0} MS, output result {1}", wt. elapsedMilliseconds, 2); 12 }). 13 ContinueWith (task) => {Console. writeLine (3 );}). 14 Wait ();View Code
Some text descriptions are also noted in the above Code. The keywords and meanings are as follows:
. Task. Factory. StartNew: Creates a Task instance, which is automatically enabled after creation. You do not need to call Start;
. ContinueWith: the meaning of the word is clear, and the meaning is "continue". The effect here is to wait until the previous Task is completed and continue to execute this Task, in this method, each task is transmitted layer by layer.
:
Note that sleep is 5s, but Stopwatch is only 4999 ms. This is a difference. This Chapter does not explain it. If you are interested, share it or study it.
2. Parallel task performance
1 // parallel task 2 var watch = new Stopwatch (); 3 // func method (cognitive feature: any length parameter, the last type is the return value type returned by the method) 4 Func <object, int> fun = (num) => 5 {6 Thread. sleep (1000*2); 7 Console. writeLine ("{0}", num); 8 return Convert. toInt32 (num); 9}; 10 var len = 5; 11 var tasks = new Task <int> [len]; 12 // start computing processing time 13 watch. start (); 14 for (int _ I = 0; _ I <len; _ I ++) 15 {16 // Task. factory. you do not need to use start17 tasks [_ I] = Task to directly enable a Task in StartNew. factory. startNew <int> (fun, _ I); 18} 19 // wait for 20 tasks in 10 s. waitAll (task, 1000*10); 21 watch. stop (); 22 Console. writeLine ("tasks total time: {0} s = {1} ms", watch. elapsedMilliseconds/1000, watch. elapsedMilliseconds );View Code
Keywords and meanings:
. Func <object, int> is a new feature of C #. The biggest difference between it and Action is that Func has returned values, and the number and type of parameters with the same length as Action
. Task. the WaitAll method has several reloads. Here we use a timeout method. After the time is set, we will not wait for the Task at the specified time, if task [] is finished within the time-out period, it passes through without waiting for the time-out period.
Effect:
There is still a statistical time query problem here, ignore
3. Paging task execution Method
1 /// <summary> 2 // execution method of Batch Tasks 3 /// </summary> 4 /// <typeparam name = "T"> parameter type </typeparam> 5 // <param name = "func"> func method </param> 6 // <param name = "list"> data to be executed </param> 7/ // <param name = "taskLen"> task count </param> 8 // <param name = "timeOut"> default task timeOut value: 30 s </param> 9/ // <returns> </returns> 10 public static int _ ExcuteTask <T> (Func <List <T>, int> func, List <T> list, int taskLen = 10, int timeOut = 30) where T: class11 {12 var result = 0; 13 // Task count 14 var tasks = new Task <int> [taskLen]; 15 var page = list. count/taskLen + (list. count % taskLen> 0? 1: 0); // The total number of items to be executed for each score has at most 16 for (var ji = 1; ji <= taskLen; ji ++) 17 {18 // use the paging method to obtain the data to be executed 19 var list01 = list. skip (ji-1) * page ). take (page ). toList (); 20 if (list01.Count <= 0) {break;} 21 var task = Task. run () => 22 {23 24 return func (list01); 25}); 26 tasks [ji-1] = task; 27} 28 // wait for 29 tasks to be executed. waitAll (tasks, 1000*1 * timeOut); 30 // get the number of successful executions 31 result = tasks. where (B => B. isCompleted ). sum (B => B. result); 32 33 return result; 34}View Code
Test code:
1 /// <summary> 2 // test the underlying data method for execution 3 /// </summary> 4 /// <param name = "list"> </param> 5 /// <returns> </returns> 6 static int _ FuncTest (List <string> list) 7 {8 9 foreach (var item in list) 10 {11 Thread. sleep (1000*2); 12 Console. writeLine ("TaskId: {1} output number {0}", item, Task. currentId); 13} 14 return list. count; 15}View Code 1 // paging task execution method 2 var listT = new List <string> (); 3 for (int _ I = 0; _ I <9; _ I ++) 4 {5 listT. add (_ I. toString (); 6} 7 watch. restart (); 8 // call the Public method of the task 9 var result = _ ExcuteTask (_ FuncTest, listT, 3); 10 watch. stop (); 11 Console. writeLine ("data to be processed: {0} items, total processed data: {1} items, use time: {2} ms", listT. count, result, watch. elapsedMilliseconds );View Code
Here we use the paging principle to distribute the parameter set to the created Task and use Task [] to process the data, here I am a little familiar with the second example. I just wrote more paging statements, and finally counted the number of successfully executed items to return them to the caller. This method is frequently used to easily record logs, I don't know if there is anything better. Please share it with me. Thank you.
:
The above is the summary of this article. I hope you will have some help. If you have any questions or questions, please communicate with each other in a timely manner.