Another set of common async / Task pitfalls, and how to avoid them

Stefan Schranz
6 min readMay 2, 2021

It was nice to see how many people took the time to read my first story on this subject (https://itnext.io/common-async-task-mistakes-and-how-to-avoid-them-fe61e2c587f), so I decided I’ll just follow up with another set of these gotchas.

Tasks start hot

Probably most of the readers are aware of the fact that an async method starts hot. But just for recap, let’s see this code:

async Task Main()
{
Console.WriteLine("Starting to wait");
await DoStuff();
Console.WriteLine("Done awaiting");
}
async Task DoStuff()
{
await Task.Delay(50);
Console.WriteLine("DoStuff writing");
}
// Output:
Starting to wait
DoStuff writing
Done awaiting

That was not a big surprise. Now let’s see the code using the hot start of a Task:

async Task Main()
{
var task = DoStuff();
await Task.Delay(100);
Console.WriteLine("Starting to wait");
await task;
Console.WriteLine("Done awaiting");
}
async Task DoStuff()
{
await Task.Delay(50);
Console.WriteLine("DoStuff writing");
}
// Output:
DoStuff writing
Starting to wait
Done awaiting

Now you can see, that the DoStuff() method completes before we even await it. We added an artifical, unrelated delay to bring the point across, but it’s clearly visible that the Task already started working.

This makes it pretty clear that a Task-backed method is nothing special, it always starts the moment it is called, just like a regular method. Awaiting it is merely a way to control program flow and shape it in a way so that sequential flow is possible where necessary, but it has nothing to do with “starting” the method.

Now I’m sure that the majority of readers was familiar with this. However, there are still a lot of small pitfalls one will regularily fall into, as it is not always obvious when a method is actually invoked.

Let’s take a common mistake for example:

async Task Main()
{
List<Task> taskList = Enumerable.Range(0, 5).Select(x => DoStuff(x)).ToList();
Console.WriteLine("Concating")…

--

--

Stefan Schranz

26 year old full stack software developer from Germany - Enthusiatic about C#, .Net and Cloud — Visit me at https://dotschranz.net/