When I first agreed to do a talk about how Async in C# really works, I thought I was an expert. I had written lots of high-throughput, high-performance async code so it should be really easy to write this talk.
As soon as I began writing the code to prove the things I knew - it turned out that I knew nothing at all and all my assumptions were wrong. The result was a much better talk where I describe the fundamentals of how Async in C# works and explain a lot of the misconceptions people, such as myself, have. So far I have delivered the talk to my colleagues at work, at Dotnet Oxford and at DDD South West - thanks for having me!
The presentation and the code samples are on GitHub and I have also recorded it as a video. For practical reasons, the video was recorded in five parts; you can see them all in one playlist or see the individual parts below.
Part 1 - Introduction
There are lots of reasons to use async - some of them are true, others are not. In the introduction we have a quick look at these.
Part 2 - Brain Teasers
A quick run through some code examples that may give you different results than you expect. It sets the stage for the next video about how it works.
Part 3 - How it works
The meat of the presentation and by far the longest video at nearly 20 minutes. It goes into detail about what really happens when you run async code and explains where threads come into play.
Part 4 - Deadlocks
If you work with ASP.Net “old” (i.e. not Core) or you write Desktop apps then you have probably heard that using
.Result can result in deadlocks. And you may have experienced that some code will only deadlock sometimes. This video builds on part 3 to explain why the deadlocks occur. It does primarily focus on ASP.Net.
Part 5 - Tips
To sum up I have collected some tips that you can use, including some on how to utilise Async to easily parallelise network writes and other async work in a way that can speed up the throughput of your code very substantially. After the last time I gave this talk, Tom Robinson kindly pointed me to these comments by David Fowler which put a bit more nuance around my tip to “just return the task”; consider your circumstances and make the choices that are right for you.