
The Rules Behind Span<T>: Why It Can't Live on the Heap or Cross an await
- كاتب موثّق
- .NET 10
محتويات المقال
Split and Substring with ReadOnlySpan<char> slicing, and the allocation graph drops. Then they make the parser asynchronous, so it can read the request body as it arrives. The build fails with CS4007: a ReadOnlySpan<char> "cannot be preserved across 'await' or 'yield' boundary." Moving the span into a field of the parser class fails too, with CS8345. The fix that gets merged calls .ToString() before every await, and the allocations the change was meant to remove come right back.
The common misconception
Span<T> is a faster array. It's a struct, so it's cheap to pass around, and like any other value it can sit in a field, be captured by a lambda or be kept in a local across an await.
Span<T> looks like an array: you index it, slice it and loop over it, and an array converts to one implicitly. Benchmarks show span-based code beating array-and-string code, and indexing a span compiles to code almost identical to indexing an array. Since C# 13, spans are even allowed inside async methods, which looks like the old rules are gone.
What actually happens
A span is a view, not storage
Span<T> holds two things: a reference to the first element and a length. It owns nothing. The reference can point into a managed array, into a string (for ReadOnlySpan<char>), into memory allocated on the stack with stackalloc, or into native memory. Slicing creates a new reference and length over the same memory, without copying, which is why input.AsSpan(7, 5) costs nothing while input.Substring(7, 5) allocates a new string. Writes through a span change the memory behind it.
Why it has to stay on the stack
stackalloc memory, that memory disappears when the method returns, so the span can't outlive the method. If it points into the middle of an array, it's an , which is relatively expensive for the garbage collector to track, so the runtime only allows them on the stack. And a span is two fields, larger than a machine word: on the heap, one thread could read the new reference with the old, longer length, and read past the end of the memory. So Span<T> is a , and the compiler enforces where it may live: not as a field of a class or a normal struct, not as an array element, not boxed, and not captured by a lambda.
Why it can't cross an await
await become fields of the compiler-generated , which moves to the heap when the method has to wait. A span stored there would break every rule above. Since C# 13, you can declare spans in async methods, as long as no span is still needed after an await; otherwise the compiler reports CS4007. The same applies to yield return in iterators.
Memory<T> is the view that can wait
Memory<T> is the view that can waitMemory<T> describes the same kind of slice, but it's an ordinary struct: an object, an index and a length. It can be a field, sit in an array and live across await. It can't point at stack memory, and reaching the data goes through its .Span property, which costs a little more than using a span directly. The pattern is simple: hold Memory<T> across asynchronous boundaries, and take .Span for each synchronous step.
Keeping a slice across an await
Audit.LogAsync stands in for any awaited call:
using System.Text;public static class CommandReader{ public static async Task<string> ReadCommandAsync(Stream stream) { var buffer = new byte[256]; int read = await stream.ReadAsync(buffer); Span<byte> line = buffer.AsSpan(0, read); // a view into buffer await Audit.LogAsync(read); int space = line.IndexOf((byte)' '); // error CS4007 return Encoding.ASCII.GetString(space < 0 ? line : line[..space]); }}using System.Text;public static class CommandReader{ public static async Task<string> ReadCommandAsync(Stream stream) { var buffer = new byte[256]; int read = await stream.ReadAsync(buffer); Memory<byte> line = buffer.AsMemory(0, read); // a view that can wait await Audit.LogAsync(read); return CommandName(line.Span); // back to a Span for synchronous work } private static string CommandName(ReadOnlySpan<byte> line) { int space = line.IndexOf((byte)' '); return Encoding.ASCII.GetString(space < 0 ? line : line[..space]); }}line is still needed after the await, so it would have to become a field of the state machine. The second keeps a Memory<byte> over the same buffer, which can safely wait, and hands a span to a synchronous helper afterwards. Neither version copies the bytes.
When a type needs to hold a span
ref struct, which then follows the same stack-only rules:
public ref struct FieldReader(ReadOnlySpan<char> line){ private ReadOnlySpan<char> _rest = line; // allowed: FieldReader is a ref struct public bool TryRead(out ReadOnlySpan<char> field) { if (_rest.IsEmpty) { field = default; return false; } int comma = _rest.IndexOf(','); field = comma < 0 ? _rest : _rest[..comma]; _rest = comma < 0 ? default : _rest[(comma + 1)..]; return true; }}await, store a Memory<T> or ReadOnlyMemory<T> instead.
Array vs Span vs Memory
T[] | Span<T> | Memory<T> | |
|---|---|---|---|
ref struct | |||
await or in a lambda | |||
How to apply it in your project
Use spans for synchronous work Write parsing, formatting and searching helpers against ReadOnlySpan<T>orSpan<T>, and keep them free ofawait.Use Memory at async boundaries When a slice must survive an await, or be stored in a class, passMemory<T>orReadOnlyMemory<T>, and call.Spaninside the synchronous helper.Don't silence CS4007 with copies When the compiler rejects a span across an await, move the span work into a synchronous method instead of addingToArray()orToString().Respect the lease Never keep a Memory<T>after the call that received it has finished, especially over pooled buffers. Copy the data if it must live longer.
Key takeaways
Span<T>is a reference plus a length over memory it doesn't own, not a faster array.It may point at stack memory and holds an interior pointer, so it can only live on the stack: no class fields, lambdas or values kept across an await.Memory<T>is the view that can be stored and awaited; take.Spanfor each synchronous step.The compiler protects spans, not Memory<T>: never use one after the lease of the method that received it.
التعليقات (0)