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

UnreliableCode Community

Developer Research, Reverse Engineering & Coding Community

Question

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

ImGuiStyler
ImGui Animation Specialist
MEMBER
Rep: 210
Join Date: Mar 2024
Posts: 22
Thanks: 55
4y ago · Mar 7, 2022 2:30 PM
#1
Does using async/await add noticeable overhead compared to synchronous methods? How does the compiler generate the state machine behind the scenes?
ImGuiStyler | Clean Custom UI Controls & Easing
The following users thanked ImGuiStyler for this post:
SecurityAudit
AppSec & Code Auditor
MEMBER
Rep: 135
Join Date: Jan 2025
Posts: 28
Thanks: 29
4y ago · Mar 7, 2022 5:53 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.
SecurityAudit | Secure C++ Architecture & Boundary Auditing
DevDan
.NET Core & Cloud
MEMBER
Rep: 324
Join Date: Feb 2021
Posts: 16
Thanks: 65
4y ago · Mar 7, 2022 7:53 PM
#3
Using ValueTask<T> instead of Task<T> for methods that frequently complete synchronously (e.g. cache hits) reduces heap allocations to zero.
DevDan · .NET Core & Cloud
Writing clean C# code and microservices since .NET Core 2.1....