Developer knowledge network ยท moderated exchange

Onbetrouwbare Code-gemeenschap

Ontwikkelaarsonderzoek, reverse engineering en coderingsgemeenschap

Knowledge indexLive
4Categories
919Threads
2.8KBerichten
Discussion

Why ref struct cannot be used in async methods, generics, or captured in lambdas [StackOverflow Architecture Guide]

dotnet_runtime_architect
.NET Core Specialist
MEMBER
Vertegenwoordiger: 103
Datum van deelname: Apr 2018
Berichten: 40
Bedankt: 24
1 maanden geleden ยท Jul 13, 2026 10:26 AM
#1

Understanding the CLR constraints on ref struct types (like Span<T> and ReadOnlySpan<T>):

Because ref struct instances contain interior pointers directly into stack memory, the CLR guarantees they never escape to the managed heap where they could outlive their stack frames.

Forbidden in C#:

  • Cannot be boxed (object o = mySpan; // Compiler Error)
  • Cannot be a field of a normal class or struct
  • Cannot be used in async methods across await boundaries (because async state machines are lifted to the heap upon suspension!)
  • Cannot be captured in lambda closures.

In .NET, use Memory<T> / ReadOnlyMemory<T> when buffer references need to cross async/await boundaries safely!

csharp_async_master
Async & Task Expert
MEMBER
Vertegenwoordiger: 57
Datum van deelname: Mar 2019
Berichten: 18
Bedankt: 40
1 maanden geleden ยท Jul 13, 2026 3:55 PM
#2

Memory<T> is a regular struct that wraps an array or MemoryManager, so it is completely safe to store in classes or await in async methods.

unsafe_memory_wizard
Unsafe & P/Invoke
MEMBER
Vertegenwoordiger: 160
Datum van deelname: Jul 2022
Berichten: 10
Bedankt: 38
1 maanden geleden ยท Jul 14, 2026 5:52 AM
#3

Clear architectural breakdown of Span vs Memory lifetime boundaries.