10 rules for writing asynchronous code in C#

Bending the Clean Architecture Principles

Anthony Trad
6 min readJun 25, 2023
Async await meme

Introduction

Imagine you’re a chef in a kitchen full of ingredients, some fresh, some a bit past their prime, all thanks to Microsoft’s “We never throw anything away” policy. This is what programming asynchronously in C# is like — an overwhelming mix of new and old syntax all in one big pot.

This pot can turn to be a big ball of code mud, you could end up with the coding equivalent of food poisoning: thread starvation, deadlocks, or even the dreaded application crashes. Most of these problems boil down to a lack of understanding of the underlying concepts such as state machines, the thread pool, context switching etc...

I drafted a document for my team explaining those concepts and decided to narrow it down to a simple 10 rule cook book here as those are pretty common in the industry. There’s a lot more than 10 rules, feel free to let me know if you want the rest !

1) Do not use Async void

From all the rules, this one is the most critical potentially crashing your whole application. async void can’t be tracked and if any exception is triggered, it will crash the whole application.

--

--

Anthony Trad

Senior Software Engineer focused on .NET and the Cloud. Reconsidering major principles and patterns, ideas are my own.