Home / Forums / What is the actual overhead of async/await state machines in C#? [Discussion #10]

UnreliableCode Community

Developer Research, Reverse Engineering & Coding Community

Question

What is the actual overhead of async/await state machines in C#? [Discussion #10]

AimbotMath
Trigonometry & Smoothing
MEMBER
Rep: 285
Join Date: Nov 2023
Posts: 27
Thanks: 73
4y ago · Mar 16, 2022 8:06 PM
#1
Does using async/await add noticeable overhead compared to synchronous methods? How does the compiler generate the state machine behind the scenes?
AimbotMath · Angular Normalization & Smooth Angles
The following users thanked AimbotMath for this post:
DisasmGeek
Capstone & Keystone Specialist
MEMBER
Rep: 160
Join Date: Dec 2024
Posts: 21
Thanks: 38
4y ago · Mar 16, 2022 10:12 PM
#2
When a method is marked async, the Roslyn compiler rewrites it into an IAsyncStateMachine struct. If the awaited task completes synchronously (like ValueTask.CompletedTask), it executes with zero allocation and near-zero overhead! If it yields, a heap frame is allocated to hold local variables until completion.
DisasmGeek · Capstone / Keystone Engine Integration
CSharpNinja
Senior .NET Developer
VIP
Rep: 329
Join Date: Jan 2020
Posts: 16
Thanks: 75
4y ago · Mar 17, 2022 1:12 AM
#3
Using ValueTask<T> instead of Task<T> for methods that frequently complete synchronously (e.g. cache hits) reduces heap allocations to zero.
CSharpNinja · Senior .NET Developer
C# enthusiast, building distributed backend services and hig...