Developer knowledge network · moderated exchange

UnreliableCode қауымдастығы

Әзірлеушілерді зерттеу, кері инженерия және кодтау қауымдастығы

Knowledge indexТірі
4Categories
919Threads
2.8KЖазбалар
Discussion

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

csharp_async_master
Async & Task Expert
MEMBER
Өкіл: 57
Қосылу күні: Mar 2019
Хабарламалар: 18
Рахмет: 40
3 апта бұрын · 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
Өкіл: 103
Қосылу күні: Apr 2018
Хабарламалар: 40
Рахмет: 24
3 апта бұрын · 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
Өкіл: 156
Қосылу күні: Jan 2022
Хабарламалар: 10
Рахмет: 16
3 апта бұрын · 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.