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

--

--

Stefan Schranz

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