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.