🔧 Fix a Ref Struct Breaking an Async Iterator
A ref struct like Span<T> or ReadOnlySpan<T> can never be stored as a field of a class, and an async iterator method – one using yield return inside an async IAsyncEnumerable<T> method – compiles down to a state machine that is a class, needing to persist its local variables as fields across every await boundary. The compiler refuses to let a ref struct live as a local across a yield return or await inside that kind of method, even though the exact same usage compiles cleanly in an ordinary synchronous iterator or a plain async method that never yields.
🔧 The Problem
public async IAsyncEnumerable<int> ReadValuesAsync(byte[] buffer)
{
Span<byte> span = buffer; // ref struct local
await Task.Delay(1);
// CS4013 / CS8352-style error here: span cannot be used across an
// await, because the async iterator's state machine would need to
// store it as a field, and ref structs can never be stored that way.
yield return span[0];
}
✅ Fix: Keep the Ref Struct’s Lifetime Inside One Synchronous Slice
- Keep the ref struct fully inside a single synchronous slice of the method, between await and yield points, copying whatever value you actually need out of it into an ordinary local before crossing the next await or yield return.
- If the data genuinely needs to survive across awaits, back it with Memory<T> instead of Span<T> for that piece – Memory<T> is an ordinary struct, not a ref struct, built specifically for the case of surviving async boundaries.
- Split the method into a synchronous local function that does the Span<T>-based processing and returns a plain value, called from inside the async iterator only at points where no ref struct needs to persist across a yield.
🚨 Why This Is Dangerous
- Reaching for Span<T> inside async code purely because it’s the faster option, without checking this constraint first, can mean rewriting a chunk of otherwise-working logic from scratch the moment the compiler error shows up, instead of designing around Memory<T> from the start.
A ref struct’s speed comes from never leaving the stack – an async state machine’s whole job is moving locals somewhere that can survive past it.



