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

UnreliableCode Community

Developer Research, Reverse Engineering & Coding Community

Question

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

OffsetHunter
RTTI & NetVar Dumper
MEMBER
Rep: 175
Join Date: Jul 2024
Posts: 20
Thanks: 44
4y ago · Mar 25, 2022 8:54 AM
#1
Does using async/await add noticeable overhead compared to synchronous methods? How does the compiler generate the state machine behind the scenes?
OffsetHunter · RTTI TypeDescriptors & NetVars
The following users thanked OffsetHunter for this post:
GhostHunter_x
Unity & Phasmo Modder
VIP
Rep: 275
Join Date: Apr 2023
Posts: 17
Thanks: 71
4y ago · Mar 25, 2022 11:17 AM
#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.
GhostHunter_x · Phasmophobia & Unity Reverser
GhostAI, Sanity, EMF & Evidence inspection
PixelCraft
ImGui UI Hacker
MEMBER
Rep: 344
Join Date: Mar 2022
Posts: 7
Thanks: 92
4y ago · Mar 26, 2022 5:17 PM
#3
Using ValueTask<T> instead of Task<T> for methods that frequently complete synchronously (e.g. cache hits) reduces heap allocations to zero.
PixelCraft · ImGui UI Hacker
Creating custom Dear ImGui themes, graphs, docking layouts, ...