Skip to content

Compiler transformation into state machine

Context: The C# compiler transforms async methods into a state machine. This allows the method to suspend and resume at await points without blocking.

using System;
using System.Threading.Tasks;
public class Example
{
public async Task ExampleAsync()
{
Console.WriteLine("Start");
await Task.Delay(1000);
Console.WriteLine("Resumed");
}
}

The compiler generates a struct with states (0 = before first await, 1 = after, etc.), preserving local variables.

  • No threading magic: the method runs on the original synchronization context after the await.
  • Efficient: no extra thread is created for waiting.

UI applications: In WPF or WinForms, await returns to the UI thread automatically (if not using ConfigureAwait(false)).

Example: Async in depth explains the state machine.