Recommendation 81: Use parallel to simplify the use of tasks in a synchronous state
In namespace System.Threading.Tasks, there is a static class parallel that simplifies the operation of tasks in the synchronized state. Parallel mainly provides 3 useful methods: For, ForEach, Invoke.
The For method is primarily used to handle parallel operations on array elements, as follows:
static void Main (string [] args) { int [] nums =
new
int [] {
1 ,
2 ,
3 ,
4
}; Parallel.For (
0 , Nums. Length, (i) =>
" Some work code for the element {1} corresponding to the array index {0} ... " ,i, Nums[i]); }); Console.readkey (); }
The output is:
Some work code for the element 1 corresponding to the array index 0 ...
Some work code for the element 3 corresponding to the array index 2 ...
Some work code for the element 2 corresponding to the array index 1 ...
Some work code for the element 4 corresponding to the array index 3 ...
As you can see, the work code is not traversed in the index order of the array. This is because our traversal is parallel, not sequential. So, here's a tip: if our output has to be synchronous or must be sequential, then parallel should not be used.
The Foreach method is primarily used to handle parallel operations of generic collection elements, as follows:
static void Main (string [] args) {List <int > nums = new list<int > {1 , 2 , 3 , 4 }; Parallel.ForEach (Nums, (item) => {Console.WriteLine ( " Some work code for collection element {0} ... "
The output is:
Some work code for collection element 1 ...
Some work code for collection element 4 ...
Some work code for collection element 3 ...
Some work code for collection element 2 ...
With the For and foreach methods, the parallel type automatically assigns us a task to do some work on the element. Of course we can also use task directly, but the above form is more concise in syntax.
The Invoke method of parallel simplifies the start of a set of parallel operations, which implicitly initiates a task. The method accepts the params action[] parameter as follows:
Static voidMain (string[] args) {Parallel.Invoke ()={Console.WriteLine ("Task 1 ..."); }, () ={Console.WriteLine ("Task 2 ..."); }, () ={Console.WriteLine ("Task 3 ..."); }); Console.readkey (); }
The output is:
Task 2 ...
Task 3 ...
Task 1 ...
Similarly, because all tasks are parallel, it does not guarantee precedence.
Turn from: 157 recommendations for writing high-quality code to improve C # programs Minjia
157 recommendations for writing high-quality code to improve C # programs--Recommendation 81: Use parallel to simplify task usage in a synchronous state