[英]Tasks are slower when running in parallel
I have troubles understanding why this code:我很难理解为什么这个代码:
// Example #1
foreach (var task in tasks)
{
task.Start();
task.Wait();
}
runs much, much faster than:运行速度比:
// Example #2
foreach (var task in tasks)
{
task.Start();
}
foreach (var task in tasks)
{
task.Wait();
}
While example #1 executes all tasks in 1-2 seconds, example #2 takes almost 20s to execute.示例 #1 在 1-2 秒内执行所有任务,示例 #2 需要将近 20 秒才能执行。 Variable
tasks
is of type Task[]
.变量
tasks
是Task[]
类型。
There is about a dozen of tasks in array, and each takes 500-1000ms to execute.阵列中大约有十几个任务,每个任务需要 500-1000 毫秒来执行。 There is no CPU bound, because tasks just send HTTP requests to server.
没有 CPU 限制,因为任务只是向服务器发送 HTTP 请求。
It doesn't make any sense for me.这对我来说没有任何意义。
I solved my problem with @StephenCleary helper library: https://github.com/StephenCleary/AsyncEx 我用@StephenCleary帮助程序库解决了我的问题: https : //github.com/StephenCleary/AsyncEx
AsyncContext.Run(async () =>
{
foreach (var task in tasks) task.Start();
await Task.WhenAll(tasks);
});
Now it runs as quickly as #1 example but also correctly waits before all requests are complete. 现在,它的运行速度与#1示例一样快,而且可以正确地等待所有请求完成。
Can you use this: 你可以使用这个:
class Program
{
static void Main(string[] args)
{
Task.Run(async () => {
List<Task> tasks = new List<Task>();
for (int i = 0; i < 10; i++)
{
int x = i; // closure
tasks.Add(Task.Factory.StartNew(() => Console.WriteLine(x.ToString())));
}
await Task.WhenAll(tasks.ToArray());
});
Console.ReadKey();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.