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

C#.NetParallel ProcessingTask Parallel-LibraryAsync Await

C# Problem Overview


In case I do not 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 DoWork2 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();
		}
	}
}

C# Solutions


Solution 1 - C#

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 even in the presence of failures (faulted or canceled tasks). Awaiting manually in sequence would cause unexpected concurrency because the part of your program that wants to wait will actually continue early.

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

Solution 2 - C#

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).

Solution 3 - C#

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

Solution 4 - C#

(Disclaimer: This answer is taken/inspired from Ian Griffiths' TPL Async course on Pluralsight)

Another reason to prefer WhenAll is Exception handling.

Suppose you had a try-catch block on your DoWork methods, and suppose they were calling different DoTask methods:

static async Task DoWork1() // modified with try-catch
{
    try
    {
        var t1 = DoTask1Async("t1.1", 3000);
        var t2 = DoTask2Async("t1.2", 2000);
        var t3 = DoTask3Async("t1.3", 1000);

        await t1; await t2; await t3;

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

In this case, if all 3 tasks throw exceptions, only the first one will be caught. Any later exception will be lost. I.e. if t2 and t3 throws exception, only t2 will be catched; etc. The subsequent tasks exceptions will go unobserved.

Where as in the WhenAll - if any or all of the tasks fault, the resulting task will contain all of the exceptions. The await keyword still always re-throws the first exception. So the other exceptions are still effectively unobserved. One way to overcome this is to add an empty continuation after the task WhenAll and put the await there. This way if the task fails, the result property will throw the full Aggregate Exception:

static async Task DoWork2() //modified to catch all exceptions
{
    try
    {
        var t1 = DoTask1Async("t1.1", 3000);
        var t2 = DoTask2Async("t1.2", 2000);
        var t3 = DoTask3Async("t1.3", 1000);

        var t = Task.WhenAll(t1, t2, t3);
        await t.ContinueWith(x => { });

        Console.WriteLine("DoWork1 results: {0}", String.Join(", ", t.Result[0], t.Result[1], t.Result[2]));
    }
    catch (Exception x)
    {
        // ...
    }
}

Solution 5 - C#

The other answers to this question offer up technical reasons why await Task.WhenAll(t1, t2, t3); is preferred. This answer will aim to look at it from a softer side (which @usr alludes to) while still coming to the same conclusion.

await Task.WhenAll(t1, t2, t3); is a more functional approach, as it declares intent and is atomic.

With await t1; await t2; await t3;, there is nothing preventing a teammate (or maybe even your future self!) from adding code between the individual await statements. Sure, you've compressed it to one line to essentially accomplish that, but that doesn't solve the problem. Besides, it's generally bad form in a team setting to include multiple statements on a given line of code, as it can make the source file harder for human eyes to scan.

Simply put, await Task.WhenAll(t1, t2, t3); is more maintainable, as it communicates your intent more clearly and is less vulnerable to peculiar bugs that can come out of well-meaning updates to the code, or even just merges gone wrong.

Solution 6 - C#

It is as simple as this.

If you have multiple http calls IEnumerable to either an external api or database, use WhenAll to execute requests parallelly instead of awaiting for a single call to complete then proceed with others.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionavoView Question on Stackoverflow
Solution 1 - C#usrView Answer on Stackoverflow
Solution 2 - C#Marcel PopescuView Answer on Stackoverflow
Solution 3 - C#LukazoidView Answer on Stackoverflow
Solution 4 - C#Maverick MeerkatView Answer on Stackoverflow
Solution 5 - C#rarrarrarrrView Answer on Stackoverflow
Solution 6 - C#Sohail ShaghasiView Answer on Stackoverflow