C# & CLR Internals (50 Qs)•Part 1: Core Language, CLR & Memory Architecture (1 - 10)
How does the `async` / `await` State Machine work under the hood?
senior LevelAsync & PromisesSystem Design
In Simple Words:
When the Roslyn compiler encounters an async method, it rewrites the method into a generated struct implementing IAsyncStateMachine:
- When execution hits
await task, it checkstask.IsCompleted. - If completed, execution continues synchronously without thread switching.
- If not completed, the state machine captures the execution context, registers a callback hook (
awaiter.UnsafeOnCompleted), and yields the thread back to theThreadPool. - When the I/O operation completes, a thread pool worker resumes the state machine from the saved state index (
MoveNext()).