Home » c# » Why should I prefer single 'await Task.WhenAll' over multiple awaits?

Why should I prefer single 'await Task.WhenAll' over multiple awaits?

Posted by: admin November 29, 2017 Leave a comment

Questions:

In case I don’t care about the order of task completion and just need them all to complete, should I still use await Task.WhenAll instead of multiple await? E.g, is DoWord2 below a preferred method to DoWork1 (and why?):

using System;
using System.Threading.Tasks;

namespace ConsoleApp
{
    class Program
    {
        static async Task<string> DoTaskAsync(string name, int timeout)
        {
            var start = DateTime.Now;
            Console.WriteLine("Enter {0}, {1}", name, timeout);
            await Task.Delay(timeout);
            Console.WriteLine("Exit {0}, {1}", name, (DateTime.Now - start).TotalMilliseconds);
            return name;
        }

        static async Task DoWork1()
        {
            var t1 = DoTaskAsync("t1.1", 3000);
            var t2 = DoTaskAsync("t1.2", 2000);
            var t3 = DoTaskAsync("t1.3", 1000);

            await t1; await t2; await t3;

            Console.WriteLine("DoWork1 results: {0}", String.Join(", ", t1.Result, t2.Result, t3.Result));
        }

        static async Task DoWork2()
        {
            var t1 = DoTaskAsync("t2.1", 3000);
            var t2 = DoTaskAsync("t2.2", 2000);
            var t3 = DoTaskAsync("t2.3", 1000);

            await Task.WhenAll(t1, t2, t3);

            Console.WriteLine("DoWork2 results: {0}", String.Join(", ", t1.Result, t2.Result, t3.Result));
        }


        static void Main(string[] args)
        {
            Task.WhenAll(DoWork1(), DoWork2()).Wait();
        }
    }
}
Answers:

Yes, use WhenAll because it propagates all errors at once. With the multiple awaits you lose errors if one of the earlier awaits throws.

Another important difference is that WhenAll will wait for all tasks to complete. A chain of await would abort waiting at the first exception but execution of non-awaited tasks continues. This causes unexpected concurrency.

I think it also makes reading the code easier because the semantics that you want are directly documented in code.

Questions:
Answers:

My understanding is that the main reason to prefer Task.WhenAll to multiple awaits is performance / task “churning”: the DoWork1 method does something like this:

  • start with a given context
  • save the context
  • wait for t1
  • restore the original context
  • save the context
  • wait for t2
  • restore the original context
  • save the context
  • wait for t3
  • restore the original context

By contrast, DoWork2 does this:

  • start with a given context
  • save the context
  • wait for all of t1, t2 and t3
  • restore the original context

Whether this is a big enough deal for your particular case is, of course, “context-dependent” (pardon the pun).

Questions:
Answers:

An asynchronous method is implemented as a state-machine. It is possible to write methods so that they are not compiled into state-machines, this is often referred to as a fast-track async method. These can be implemented like so:

public Task DoSomethingAsync()
{
    return DoSomethingElseAsync();
}

When using Task.WhenAll it is possible to maintain this fast-track code while still ensuring the caller is able to wait for all tasks to be completed, e.g.:

public Task DoSomethingAsync()
{
    var t1 = DoTaskAsync("t2.1", 3000);
    var t2 = DoTaskAsync("t2.2", 2000);
    var t3 = DoTaskAsync("t2.3", 1000);

    return Task.WhenAll(t1, t2, t3);
}