Back to results for “Asynchronous Programming”
C# › Asynchronous Programming

How does the compiler transform an async method into a state machine, and why does this matter for understanding performance?

Advanced

Answer

The compiler rewrites an async method into a compiler-generated struct or class implementing IAsyncStateMachine, with a numeric state field tracking progress and each 'await' becoming a suspend/resume point — this transformation has real allocation costs (especially for a class-based state machine when the method captures local variables or is a class-based async method), which is why hot-path async methods sometimes prefer ValueTask over Task to reduce allocations.
// Conceptual illustration of what the compiler generates behind the scenes:
// class MethodNameStateMachine : IAsyncStateMachine {
//   int state;
//   TaskAwaiter awaiter;
//   void MoveNext() { /* resumes execution from the last await point */ }
// }
Real-world example Understanding why a hot-path async method with many local variables can have measurably higher allocation overhead than an equivalent synchronous one.

Common follow-ups: Under what conditions does the compiler generate a STRUCT-based state machine instead of a class-based one, and why does that matter for allocations?