When you mark a method async, the Roslyn compiler transforms the method into an IAsyncStateMachine struct behind the scenes.
public async Task<string> FetchDataAsync()
{
var result = await _httpClient.GetStringAsync("https://api.example.com");
return result.ToUpper();
}Internal Lowering:
- Roslyn generates a hidden struct state machine with an
int _statefield (-1= running,0= waiting on awaiter,-2= completed). - When execution hits
await, it callsawaiter.IsCompleted. Iffalse, it hooks a continuation delegate and returns the uncompletedTaskto the caller. - 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!