Developer knowledge network · moderated exchange

UnreliableCode Topluluğu

Geliştirici Araştırması, Tersine Mühendislik ve Kodlama Topluluğu

Knowledge indexCanlı
4Categories
919Threads
2.8KGönderiler
Discussion

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

csharp_async_master
Async & Task Expert
MEMBER
Temsilci: 57
Katılım Tarihi: Mar 2019
Gönderiler: 18
Teşekkürler: 40
3 hafta önce · 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
Temsilci: 103
Katılım Tarihi: Apr 2018
Gönderiler: 40
Teşekkürler: 24
3 hafta önce · 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
Temsilci: 156
Katılım Tarihi: Jan 2022
Gönderiler: 10
Teşekkürler: 16
3 hafta önce · 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.