It is recommended that 82:parallel be simplified but not equal to the task default behavior
Recommendation 81 Speaking of the use of parallel, do not know whether people notice the wording used in the text: in a synchronized state to simplify the use of task. That is, when you run the For, foreach method in parallel, the caller thread (the main thread in the example) is blocked. Parallel the task is assigned to the CLR thread pool for processing, but the caller waits until all the relevant work in the thread pooling has been completed. A static class that represents parallelism parallel even provides an invoke method, but does not provide a BeginInvoke method at the same time, which also illustrates this problem to some extent.
When using a task, we use the Start method most often (the task also provides a runsynchronously), which does not block the caller thread. As shown below:
Static void Main () { new Task () = { while ( true) { } }); T.start (); Console.WriteLine ("The main thread is about to end "); Console.readkey ();
The output is:
The main thread is about to end
Using parallel to perform similar functions, the main thread is blocked:
Static void Main () { // Here you can also use the Invoke method parallel.for (01, (i) = = { while (true) { } }); Console.WriteLine ("The main thread is about to end "); Console.readkey ();
If you execute this code, there will never be an output.
Parallel programming means that the runtime allocates the task to as many CPUs as possible in the background, although it uses task in the background to manage it, but that does not mean that it is equivalent to async.
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-recommended 82:parallel simplification but not equivalent to task default behavior