Parallel.ForEach() 与 foreach(IEnumerable<T>.AsParallel()) [英] Parallel.ForEach() vs. foreach(IEnumerable&lt;T&gt;.AsParallel())

查看:30
本文介绍了Parallel.ForEach() 与 foreach(IEnumerable<T>.AsParallel())的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

呃,我正在尝试使用 Reflector 在 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 => {
   ...
});

乙:

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.

第一个接受匿名委托,并针对所有不同的项目在此代码上并行运行多个线程.

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

第二个在这种情况下不是很有用.简而言之,它旨在对多个线程进行查询,并将结果组合起来,然后再次将其提供给调用线程.所以 foreach 语句上的代码总是在 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.

只有在 AsParallel() 调用右侧的 linq 查询中执行一些昂贵的操作时才有意义,例如:

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

这篇关于Parallel.ForEach() 与 foreach(IEnumerable<T>.AsParallel())的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆