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

UnreliableCode Community

Developer Research, Reverse Engineering & Coding Community

Question

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

EventDriven
Reactive Extensions
MEMBER
Rep: 160
Join Date: Sep 2022
Posts: 6
Thanks: 66
3y ago · Sep 25, 2022 5:48 PM
#1
Does using async/await add noticeable overhead compared to synchronous methods? How does the compiler generate the state machine behind the scenes?
EventDriven · Reactive Extensions
Rx.NET, event buses, and asynchronous message queues in C#....
The following users thanked EventDriven for this post:
CppModernist
Modern C++ Advocate
MEMBER
Rep: 379
Join Date: Jan 2020
Posts: 6
Thanks: 90
3y ago · Sep 25, 2022 9:10 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.
CppModernist · Modern C++ Advocate
Writing idiomatic C++20/23: ranges, modules, std::format, an...
SpanSpecialist
Zero-Copy Memory
MEMBER
Rep: 273
Join Date: Aug 2021
Posts: 7
Thanks: 33
3y ago · Sep 26, 2022 10:10 PM
#3
Using ValueTask<T> instead of Task<T> for methods that frequently complete synchronously (e.g. cache hits) reduces heap allocations to zero.
SpanSpecialist · Zero-Copy Memory
Span<T>, ReadOnlySpan<T>, and stackalloc for fast substring ...