Parallel.ForEach VS Task.Run和Task.WhenAll [英] Parallel.ForEach vs Task.Run and Task.WhenAll

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

问题描述

什么是使用Parallel.ForEach或Task.Run()启动一组任务之间的区别异步?

What are the differences between using Parallel.ForEach or Task.Run() to start a set of tasks asynchronously?

版本1:

List<string> strings = new List<string> { "s1", "s2", "s3" };
Parallel.ForEach(strings, s =>
{
    DoSomething(s);
});

2版:

List<string> strings = new List<string> { "s1", "s2", "s3" };
List<Task> Tasks = new List<Task>();
foreach (var s in strings)
{
    Tasks.Add(Task.Run(() => DoSomething(s)));
}
await Task.WhenAll(Tasks);


推荐答案

在此情况下,第二方法将异步等待任务来完成的,而不是阻断

In this case, the second method will asynchronously wait for the tasks to complete instead of blocking.

然而,有一个缺点在环 - 使用 Task.Run 使用 Parallel.ForEach ,有是<一个href=\"http://msdn.microsoft.com/en-us/library/system.collections.concurrent.partitioner.aspx\"><$c$c>Partitioner这被创建,以避免不必要使更多的任务。 Task.Run 总会让每件单任务(因为你这样做),但并行类批量工作,让你创造出比总的工作项任务少。这可以提供显著更好的整体性能,特别是当环体具有每项工作的少量

However, there is a disadvantage to use Task.Run in a loop- With Parallel.ForEach, there is a Partitioner which gets created to avoid making more tasks than necessary. Task.Run will always make a single task per item (since you're doing this), but the Parallel class batches work so you create fewer tasks than total work items. This can provide significantly better overall performance, especially if the loop body has a small amount of work per item.

如果是这样的话,您可以通过书面形式结合两种选择:

If this is the case, you can combine both options by writing:

await Task.Run(() => Parallel.ForEach(strings, s =>
{
    DoSomething(s);
}));

请注意,这可能也是在这较短的形式写成:

Note that this can also be written in this shorter form:

await Task.Run(() => Parallel.ForEach(strings, DoSomething));

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

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