在 foreach 循环中使用 parallel.foreach 和 task 之间的性能差异是什么? [英] What is the performance differences between using parallel.foreach and task inside foreach loop?

查看:23
本文介绍了在 foreach 循环中使用 parallel.foreach 和 task 之间的性能差异是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道什么是最好的方法,或者是否有任何文档/文章可以帮助我确定在正常情况下使用 Parallel.foreach 和 Task 的区别是什么?每个循环,如下所示:

I would like to know what is the best way or are there any documents/articles that can help me to identify what is the differences of using Parallel.foreach and Task within a normal for each loop, like the following:

案例 1 - Parallel.foreach:

case 1 - Parallel.foreach:

Parallel.foreach
{
  // Do SOmething thread safe: parsing an xml and then save 
  // into a DB Server thry respoitory approach
}

案例 2 - foreach 中的任务:

case 2 - Task within foreach:

foreach
{
  Task t1 = Task.factory.startNew(()=>
  {
     //Do the same thing as case 1 that is thread safe
  }
}
Task.waitall()

  • 我确实进行了自己的测试,结果显示案例 1 的性能比案例 2 好得多.比率大约是这样的:顺序 vs 案例 1 vs 案例 2 = 5s : 1s : 4s
  • 虽然案例 1 和案例 2 几乎是 1:4 ?那么这是否意味着如果我们想在循环中并行运行,我们应该总是使用 parallel.foreach 或 parallel.for 吗?

    While there are almost a 1:4 on the case 1 and case 2 ? So is it means we should always use parallel.foreach or parallel.for if we want to run in parallel within the loop?

    推荐答案

    首先,关于该主题的最佳文档是通过 C# 编写的 CLR 的第五部分.

    First, the best documentation on the subject is Part V of CLR via C#.

    http://www.amazon.com/CLR-via-C-Developer-Reference/dp/0735667454/ref=sr_1_1?ie=UTF8&qid=1376239791&sr=8-1&keywords=clr+via+c%23

    其次,我希望 Parallel.Foreach 性能更好,因为它不仅会创建任务,还会对它们进行分组.在 Jeffrey Richter 的书中,他解释说单独启动的任务将放在线程池队列中.锁定实际线程池队列有一些开销.为了解决这个问题,任务本身有他们自己创建的任务队列.这个Task所持有的任务子队列其实可以做一些不加锁的工作!

    Secondly, I would expect the Parallel.Foreach to perform better because it will not only create Tasks, but group them. In Jeffrey Richter's book, he explains that tasks that are started individually, will be put on the thread pool queue. There is some overhead to locking the actual thread pool queue. To combat this, Tasks themselves have their own queue for Tasks that they create. This task sub-queue held by the Tasks can actually do some work without locking!

    我将不得不再次阅读那一章(第 27 章),所以我不确定 Parallel.Foreach 是否以这种方式工作,但这是我期望它做的.

    I would have to read that chapter again (Chapter 27), so I am not sure that Parallel.Foreach works this way, but this is what I would expect it to do.

    他解释说,锁定是昂贵的,因为它需要访问内核级构造.

    Locking, he explains, is expensive because it requires accessing a kernel level construct.

    在任何一种情况下,都不要期望它们按顺序处理.由于上述内部结构,使用 Parallel.Foreach 比 foreach 关键字不太可能按顺序处理.

    In either case, do not expect them to process sequentially. Using Parallel.Foreach is less likely to process sequentially than the foreach keyword due to the aforementioned internals.

    这篇关于在 foreach 循环中使用 parallel.foreach 和 task 之间的性能差异是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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