الانتقال إلى المحتوى
.NETPerformance· 7 دقائق للقراءة

The Rules Behind Span<T>: Why It Can't Live on the Heap or Cross an await

A span is a view over memory it doesn't own, so the compiler keeps it on the stack. What that rules out, and how Memory<T> fills the gap.

ReadIn

مقال كل يوم يفرق معاك

22 نوفمبر 2026
  • كاتب موثّق
  • .NET 10
محتويات المقال

A team speeds up a CSV import endpoint by replacing 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

The belief: 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.

It's easy to see why. A 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.

But the speed doesn't come from being a better array. It comes from not being an array at all.

What actually happens

A span is a view, not storage

Inside, a 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

That reference is what makes the rules necessary. If the span points at 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

An async method's locals that are still needed after an 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> 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

Here is a reader that waits for an audit call between reading a line and parsing it. Audit.LogAsync stands in for any awaited call:

C# CommandReader.cs
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]);    }}

The first version doesn't compile: 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

Sometimes you want a span in a field, for example in a small parser that walks a line. That's allowed when the type is itself a ref struct, which then follows the same stack-only rules:

C# FieldReader.cs
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;    }}

If the holder has to be a class, or has to survive an await, store a Memory<T> or ReadOnlyMemory<T> instead.

Array vs Span vs Memory

QuestionT[]Span<T>Memory<T>
Owns its elementsYesNo, it's a viewNo, it's a view
Can point toA managed arrayArrays, strings, stack and native memoryArrays, strings, custom memory managers
Field of a classYesNo, only in a ref structYes
Across an await or in a lambdaYesNoYes
Best forOwning dataSynchronous processingViews that cross async boundaries

How to apply it in your project

  1. Use spans for synchronous workWrite parsing, formatting and searching helpers against ReadOnlySpan<T> or Span<T>, and keep them free of await.
  2. Use Memory at async boundariesWhen a slice must survive an await, or be stored in a class, pass Memory<T> or ReadOnlyMemory<T>, and call .Span inside the synchronous helper.
  3. Don't silence CS4007 with copiesWhen the compiler rejects a span across an await, move the span work into a synchronous method instead of adding ToArray() or ToString().
  4. Respect the leaseNever 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 .Span for each synchronous step.
  • The compiler protects spans, not Memory<T>: never use one after the lease of the method that received it.

📚 المصادر

  1. Memory-related and span types — Microsoft Learn
  2. Memory<T> and Span<T> usage guidelines — Microsoft Learn
  3. ref struct types (C# reference) — Microsoft Learn
  4. All About Span: Exploring a New .NET Mainstay — Stephen Toub, MSDN Magazine (Microsoft Learn archive)

التعليقات (0)