🔧 C#: Fix a Span Capture Throwing in an Async Local Function
Span<T> is a ref struct specifically because it can point at stack-allocated or otherwise ephemeral memory, and the C# compiler enforces that a ref struct can never be captured by a closure, boxed, or stored as a field on a heap-allocated object – because any of those would let it outlive the exact stack frame its contents might depend on. An async local function is compiled into a heap-allocated state machine so it can be suspended and resumed later, which means any variable it captures becomes a field on that state machine object – so a Span<T> parameter or local that an async local function tries to use directly fails to compile, with an error that doesn’t always make the actual stack-safety reason obvious.
🔎 The Problem
void ProcessChunk(Span<byte> buffer)
{
async Task SaveAsync()
{
await File.WriteAllBytesAsync("out.bin", buffer.ToArray());
// CS8175: Cannot use ref local 'buffer' inside an anonymous
// method, lambda expression, or local function
}
SaveAsync(); // the compiler stops you here, before it ever runs
}
✅ The Fix
- Copy the Span’s contents into a heap-allocated array (buffer.ToArray()) BEFORE entering the async local function, and pass that array in instead – the array is safe to capture because it isn’t tied to a specific stack frame the way a Span is.
- If the data genuinely needs to stay synchronous and stack-allocated for performance, keep the Span-consuming logic entirely synchronous and only hand off the already-copied, already-safe result to any async continuation that follows it.
- Treat this compiler error as a correct, useful signal rather than an obstacle to work around with unsafe code – a Span surviving into a suspended async state machine is exactly the dangling-memory scenario the type was designed to make impossible.
🚨 Why This Is Dangerous
Trying to force this to compile with unsafe pointer tricks instead of copying the data first reintroduces exactly the memory-safety bug Span<T> exists to prevent – a buffer that gets reused or freed while a suspended async continuation still holds a reference into it.
The compiler isn’t blocking you from writing async code – it’s blocking you from asking a stack-only type to survive past the point its stack frame exists.



