Parallel.ForEach()主场迎战的foreach(IEnumerable的< T> .AsParallel())主场、foreach、Parallel、ForEach

2023-09-02 21:09:53 作者:坏脾气、TM有错么。

(ERG),我试图找到在BCL这两种方法使用反射,但无法找到他们。什么是这两个片段之间的区别?

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?

答:

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

推荐答案

他们这样做完全不同的东西。

They do something quite different.

第一个采用匿名委托,并运行多个线程对这个code并行的所有不同的项目。

The first one takes the anonymous delegate, and runs multiple threads on this code in parallel for all the different items.

第二个未在这种情况下非常有用。简而言之它旨在做一个查询在多个线程,和结合的结果,并调用线程再次给它。因此,在foreach语句的code在UI线程上保持一如既往。

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.

它才有意义,如果你做一些昂贵的LINQ查询到进行AsParallel()通话的权利,如:

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