Developer knowledge network · moderated exchange

Społeczność UnreliableCode

Badania programistów, inżynieria wsteczna i społeczność programistów

Knowledge indexNa żywo
4Categories
919Threads
2.8KPosty
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
Rozpustnik: 103
Data dołączenia: Apr 2018
Posty: 40
Dzięki: 24
1 miesięcy temu · 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
Rozpustnik: 57
Data dołączenia: Mar 2019
Posty: 18
Dzięki: 40
1 miesięcy temu · 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
Rozpustnik: 160
Data dołączenia: Jul 2022
Posty: 10
Dzięki: 38
1 miesięcy temu · Jul 14, 2026 5:52 AM
#3

Clear architectural breakdown of Span vs Memory lifetime boundaries.