Skip to content
  • Home
  • About
  • No Access
  • Privacy Policy
Bits of .NET
Bits of .NET
  • C#
  • Asp.Net Core
  • SQL
  • Windows
  • WordPress
  • AI
  • JavaScript
  • CSS
  • MORE
    • HTML
    • Ajax
    • Git
    • Docker
    • Kubernetes
    • Photoshop
    • Visual Studio

Bits of .NET

Daily micro-tips for C#, SQL, performance, and scalable backend engineering.

  • C#
  • Asp.Net Core
  • SQL
  • Windows
  • WordPress
  • AI
  • JavaScript
  • CSS
  • MORE
    • HTML
    • Ajax
    • Git
    • Docker
    • Kubernetes
    • Photoshop
    • Visual Studio
C#

C#: Fix a Ref Struct Breaking an Async Iterator

- 20.11.26 - ErcanOPAK

🔧 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.

— C# Best Practice

Related posts:

C#: Fix a Record's With Expression That Copies a Reference Instead of Deep-Copying It

C#: Fix a Record's With Expression That Copies a Reference Instead of Deep-Copying It

Write Cleaner Business Logic Using C# Switch Expressions

Write Cleaner Business Logic Using C# Switch Expressions

Exceptions Used for Flow Control

Exceptions Used for Flow Control

Views: 8
Found this useful? Share it
XLinkedInWhatsApp

Post navigation

Windows 11: Fix Nearby Share Failing Only on 5GHz Wi-Fi
C#: Fix a Partial Property Losing Its Backing Field Attribute

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Most Read

  1. 01How to make theater mode the default for Youtube 1,079 views
  2. 02How to add default value for Entity Framework migrations for DateTime and Bool 997 views
  3. 03Get the User Name and Domain Name from an Email Address in SQL 996 views
  4. 04Get the First and Last Word from a String or Sentence in SQL 873 views
  5. 05How to select distinct rows in a datatable in C# 868 views
  6. 06How to enable, disable and check if Service Broker is enabled on a database in SQL Server 671 views
  7. 07Add Constraint to SQL Table to ensure email contains @ 629 views
  8. 08Average of all values in a column that are not zero in SQL 584 views
  9. 09How to use Map Mode for Vertical Scroll Mode in Visual Studio 561 views
Bits of .NET

Daily micro-tips for C#, SQL, performance, and scalable backend engineering.

Social

  • ErcanOPAK.com
  • GoodReads
  • LetterBoxD
  • Linkedin
  • The Blog
  • Twitter
Back to top
© 2026 Bits of .NET | Built with Xblog Plus free WordPress theme by wpthemespace.com