Task.WhenAll in a Nutshell

Nelson Parente
5 min readJul 19, 2021
Photo by Ethan Robertson on Unsplash

What’s up boys and girls! As some of you already know I’m a big enthusiast of asynchronism, I find it a truly beautiful concept and I always try to make the best of it on my code and even on my other daily tasks, such as code reviews.

If you haven't had the chance to read my other articles on asynchronism take a look at them, the concepts talked about in them are the backbone of this article topic.

This article will focus on one special method that is the Task.WhenAll and see what it does, how to use it to boost our code performance, and handle exceptions when using it.

In the end, my goal is that if you agree with my insights and refactor your code according to them you feel like a chef when finishing a perfect meal, after all, programming and cooking are not so different if you look at it in a very abstract way!

public static Task WhenAll (params Task[] tasks);

Task.WhenAll creates a task that will complete when all of the supplied tasks have been completed. It's pretty straightforward what this method does, it simply receives a list of Tasks and returns a Task when all of the received Tasks completes.

This method shines when we need to await multiple independent Tasks consecutively. When we do this and simply await each Task individually we aren’t taking advantage of the async/await keywords since the code will actually run in a sequential way.

Instead of awaiting that each Task finishes before starting the next we can group that workload and execute it with the Task.WhenAll method. This will execute all the Tasks in parallel and that will reduce the execution time to the time it takes to execute the heaviest Task.

Let’s start by looking at a not so good implementation and how long it takes to complete:

I'm Jane and my work took 1006 ms
Nelson Parente