Developer knowledge network · moderated exchange

UnreliableCode コミュニティ

開発者リサーチ、リバース エンジニアリング、コーディング コミュニティ

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.