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

UnreliableCode Community

Developer Research, Reverse Engineering & Coding Community

Question

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

CanvasCrafter
UI & Custom Graphics
MEMBER
Rep: 76
Join Date: Oct 2023
Posts: 6
Thanks: 82
3y ago · Sep 16, 2022 11:12 AM
#1
Does using async/await add noticeable overhead compared to synchronous methods? How does the compiler generate the state machine behind the scenes?
CanvasCrafter · UI & Custom Graphics
Rendering smooth 2D vector shapes, bezier paths, and ImDrawL...
The following users thanked CanvasCrafter for this post:
NetCoreAddict
.NET Architect
MEMBER
Rep: 128
Join Date: Feb 2021
Posts: 6
Thanks: 58
3y ago · Sep 16, 2022 12:25 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.
NetCoreAddict · .NET Architect
Minimal APIs, dependency injection, and high-performance Web...
ImGuiAddict
GUI Developer
MEMBER
Rep: 261
Join Date: Sep 2022
Posts: 6
Thanks: 73
3y ago · Sep 17, 2022 6:25 PM
#3
Using ValueTask<T> instead of Task<T> for methods that frequently complete synchronously (e.g. cache hits) reduces heap allocations to zero.
ImGuiAddict · GUI Developer
Building debug consoles, inspector panels, and telemetry das...