It's all about the state...

What lies beneath async/await in C#?

Dariusz Pawlukiewicz

16.12.2017 dotNetConf PL

About me

  • foreverframe.net
  • devreview.pl
  • github.com/GooRiOn
  • @d_pawlukiewicz

Agenda

1. async/await in a nutshell

2. Compilation in .NET

3. Reveal the mystery...

4. Demo

5. Task.Result

6. Summary

async/await in a nutshell

STATE 1

STATE 2

Compilation in .NET

C#

VB

F#

C# compiler

VB compiler

F# compiler

IL

Metadata

JIT

01010101

Why is that important?

async/await does not exist on the IL level

... it's just a syntactic sugar

What lies beneath async/await?

STATE MACHINE

Async state machine

  • struct generated by C# compiler
  • one for each async method
  • number of states depends on number of await operators
  • kicked off by AsyncMethodBuilder
  • uses other mechnisms to schedule tasks (TimerQueue, MoveNextRunner etc.)

DEMO

Summary

  • async/await is syntactic sugar
  • compiler generates state machine instead
  • states are created by await operators
  • SM uses if/switch + goto to move across the states
  • Async methods captures context by default
  • ... therefore Task.Result might be evil

Thanks!

@d_pawlukiewicz

foreverframe.net

It's all about the state...

By goorion

It's all about the state...

  • 29