Developer knowledge network ยท moderated exchange

UnreliableCode Community

Developer Research, Reverse Engineering & Coding Community

Knowledge indexLive
4Categories
919Threads
2.8KPosts
Discussion

How the async/await State Machine works internally in C# and the CLR [StackOverflow Architecture Guide]

csharp_async_master
Async & Task Expert
MEMBER
Rep: 57
Join Date: Mar 2019
Posts: 18
Thanks: 40
3 weeks ago ยท Aug 1, 2026 1:07 PM
#1

When you mark a method async, the Roslyn compiler transforms the method into an IAsyncStateMachine struct behind the scenes.

CSHARP
public async Task<string> FetchDataAsync()
{
    var result = await _httpClient.GetStringAsync("https://api.example.com");
    return result.ToUpper();
}

Internal Lowering:

  1. Roslyn generates a hidden struct state machine with an int _state field (-1 = running, 0 = waiting on awaiter, -2 = completed).
  2. When execution hits await, it calls awaiter.IsCompleted. If false, it hooks a continuation delegate and returns the uncompleted Task to the caller.
  3. When the I/O completion port fires, the runtime calls MoveNext() on the state machine, restoring execution at the exact state without blocking an OS thread!
dotnet_runtime_architect
.NET Core Specialist
MEMBER
Rep: 103
Join Date: Apr 2018
Posts: 40
Thanks: 24
3 weeks ago ยท Aug 1, 2026 7:00 PM
#2

Understanding that async methods compile to struct state machines explains why async methods with zero awaits still incur state machine initialization overhead.

channel_concurrency
Reactive & Pipeline
MEMBER
Rep: 156
Join Date: Jan 2022
Posts: 10
Thanks: 16
3 weeks ago ยท Aug 2, 2026 8:51 AM
#3

Also explains why SynchronizationContext.Current captures execution context in UI frameworks (WPF/WinForms) unless ConfigureAwait(false) is used.