Parallel.ForEach VS Task.Factory.StartNew [英] Parallel.ForEach vs Task.Factory.StartNew

查看:114
本文介绍了Parallel.ForEach VS Task.Factory.StartNew的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么低于code片段之间的区别?将不能同时使用线程池线程?

举例来说,如果我要呼吁每一项功能的集合,

  Parallel.ForEach<项目>(项目,项目= GT; DoSomething的(项目));VS的foreach(在项目VAR项)
{
  Task.Factory.StartNew(()=> DoSomething的(项目));
}


解决方案

首先是一个更好的选择。

Parallel.ForEach,在内部,使用 分区< T> 到您的收藏分配到工作项目。它不会做一个任务每个项目,而是一批这样来降低开销参与。

第二个选项将安排每件单工作您的收藏。虽然结果将是(几乎)是相同的,这将引进更开销比必要的,尤其是对大集合,并导致整体运行时要慢一些。

FYI - 使用的分区程序可以通过使用适当的重载到Parallel.ForEach 控制如果需要的话。有关详细信息,请参阅定制Partitioners MSDN上。

主要的区别,在运行时,是第二次将采取行动异步的。这可以通过使用Parallel.ForEach做复制:

  Task.Factory.StartNew(()=> Parallel.ForEach<项目>(项目,项目= GT; DoSomething的(项目)));

通过这样做,你还是趁partitioners的,但不阻止,直到操作完成。

What is the difference between the below code snippets? Won't both be using threadpool threads?

For instance if I want to call a function for each item in a collection,

Parallel.ForEach<Item>(items, item => DoSomething(item));

vs

foreach(var item in items)
{
  Task.Factory.StartNew(() => DoSomething(item));
}

解决方案

The first is a much better option.

Parallel.ForEach, internally, uses a Partitioner<T> to distribute your collection into work items. It will not do one task per item, but rather batch this to lower the overhead involved.

The second option will schedule a single Task per item in your collection. While the results will be (nearly) the same, this will introduce far more overhead than necessary, especially for large collections, and cause the overall runtimes to be slower.

FYI - The Partitioner used can be controlled by using the appropriate overloads to Parallel.ForEach, if so desired. For details, see Custom Partitioners on MSDN.

The main difference, at runtime, is the second will act asynchronous. This can be duplicated using Parallel.ForEach by doing:

Task.Factory.StartNew( () => Parallel.ForEach<Item>(items, item => DoSomething(item)));

By doing this, you still take advantage of the partitioners, but don't block until the operation is complete.

这篇关于Parallel.ForEach VS Task.Factory.StartNew的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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