Developer knowledge network · moderated exchange

UnreliableCode Topluluğu

Geliştirici Araştırması, Tersine Mühendislik ve Kodlama Topluluğu

Knowledge indexCanlı
4Categories
919Threads
2.8KGönderiler
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
Temsilci: 103
Katılım Tarihi: Apr 2018
Gönderiler: 40
Teşekkürler: 24
1 ay önce · 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
Temsilci: 57
Katılım Tarihi: Mar 2019
Gönderiler: 18
Teşekkürler: 40
1 ay önce · 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
Temsilci: 160
Katılım Tarihi: Jul 2022
Gönderiler: 10
Teşekkürler: 38
1 ay önce · Jul 14, 2026 5:52 AM
#3

Clear architectural breakdown of Span vs Memory lifetime boundaries.