Understanding How async and await Work in .NET — Under the Hood
Asynchronous programming in .NET has become almost second nature to developers — we sprinkle async and await everywhere to make our apps responsive. But what really happens when you mark a method as async and use await inside it? Let’s demystify how the compiler, runtime, and threads work together behind the scenes. ⚙️ The Promise of async and await At first glance, async and await seem magical. You write code like this: public async Task FetchDataAsync () { var data = await GetDataFromServerAsync(); Console.WriteLine(data); } It looks sequential — first we fetch data, then we print it — but it’s actually asynchronous and non-blocking . The question is: how does the compiler make that possible? 🧩 The Compiler Trick — State Machine Transformation When you mark a method with async , the C# compiler rewrites it into a state machine — a hidden class that controls what happens before and after each await . Think of each await as a “checkpoint.” When ...