简体   繁体   中英

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. Variable tasks is of type Task[] .

There is about a dozen of tasks in array, and each takes 500-1000ms to execute. There is no CPU bound, because tasks just send HTTP requests to server.

在此处输入图片说明 在此处输入图片说明

It doesn't make any sense for me.

I solved my problem with @StephenCleary helper library: 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.

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();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM