Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Erg, I'm trying to find these two methods in the BCL using Reflector, but can't locate them. What's the difference between these two snippets?

A:

IEnumerable<string> items = ...

Parallel.ForEach(items, item => {
   ...
});

B:

IEnumerable<string> items = ...

foreach (var item in items.AsParallel())
{
   ...
}

Are there different consequences of using one over the other? (Assume that whatever I'm doing in the bracketed bodies of both examples is thread safe.)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
590 views
Welcome To Ask or Share your Answers For Others

1 Answer

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));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...