The execution of Parallel. Foreach is faster than normal ForEach.
ForEach is like the foreach loop in C#, except the foreach loop runs on a single thread and processing take place sequentially, while the Parallel. ForEach loop runs on multiple threads and the processing takes place in a parallel manner.
Parallel. ForEach uses managed thread pool to schedule parallel actions. The number of threads is set by ThreadPool.
The short answer is no, you should not just use Parallel. ForEach or related constructs on each loop that you can. Parallel has some overhead, which is not justified in loops with few, fast iterations. Also, break is significantly more complex inside these loops.
They do something quite different.
The first one takes the anonymous delegate, and runs multiple threads on this code in parallel for all the different items.
The second one not very useful in this scenario. In a nutshell it is intended to do a query on multiple threads, and combine the result, and give it again to the calling thread. So the code on the foreach statement stays always on the UI thread.
It only makes sense if you do something expensive in the linq query to the right of the AsParallel()
call, like:
var fibonacciNumbers = numbers.AsParallel().Select(n => ComputeFibonacci(n));
The second method will not be parallel the correct way to use AsParallel() in your example would be
IEnumerable<string> items = ...
items.AsParallel().ForAll(item =>
{
//Do parallel stuff here
});
The difference is, B isn't parallel. The only thing AsParallel()
does is that it wraps around a IEnumerable
, so that when you use LINQ methods, their parallel variants are used. The wrapper's GetEnumerator()
(which is used behind the scenes in the foreach
) even returns the result of the original collection's GetEnumerator()
.
BTW, if you want to look at the methods in Reflector, AsParallel()
is in the System.Linq.ParallelEnumerable
class in the System.Core
assembly. Parallel.ForEach()
is in the mscorlib
assembly (namespace System.Threading.Tasks
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With