我应该总是使用 Parallel.Foreach 因为更多的线程必须加速一切吗? [英] Should I always use Parallel.Foreach because more threads MUST speed up everything?

查看:18
本文介绍了我应该总是使用 Parallel.Foreach 因为更多的线程必须加速一切吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为每个普通的 foreach 使用一个 parallel.foreach 循环对您有意义吗?

Does it make sense to you to use for every normal foreach a parallel.foreach loop ?

我应该什么时候开始使用 parallel.foreach,只迭代 1,000,000 个项目?

When should I start using parallel.foreach, only iterating 1,000,000 items?

推荐答案

不,不是每个 foreach 都有意义.一些原因:

No, it doesn't make sense for every foreach. Some reasons:

  • 您的代码可能实际上不能并行化.例如,如果您在下一次迭代中使用到目前为止的结果"并且顺序很重要)
  • 如果您要进行聚合(例如对值求和),那么可以使用 Parallel.ForEach 来实现这一点,但您不应该盲目地这样做
  • 如果您的工作无论如何都能很快完成,那就没有任何好处,而且很可能会减慢速度
  • Your code may not actually be parallelizable. For example, if you're using the "results so far" for the next iteration and the order is important)
  • If you're aggregating (e.g. summing values) then there are ways of using Parallel.ForEach for this, but you shouldn't just do it blindly
  • If your work will complete very fast anyway, there's no benefit, and it may well slow things down

基本上任何事情都不应盲目地进行线程处理.想想并行化在什么地方有意义.哦,并衡量影响以确保收益值得增加的复杂性.(对于调试之类的事情更难.)TPL 很棒,但它不是免费的午餐.

Basically nothing in threading should be done blindly. Think about where it actually makes sense to parallelize. Oh, and measure the impact to make sure the benefit is worth the added complexity. (It will be harder for things like debugging.) TPL is great, but it's no free lunch.

这篇关于我应该总是使用 Parallel.Foreach 因为更多的线程必须加速一切吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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