Developer knowledge network · moderated exchange

Сообщество UnreliableCode

Сообщество разработчиков, обратного проектирования и кодирования

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
Представитель: 103
Дата присоединения: Apr 2018
Сообщения: 40
Спасибо: 24
1 месяцев назад · 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
Представитель: 57
Дата присоединения: Mar 2019
Сообщения: 18
Спасибо: 40
1 месяцев назад · 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
Представитель: 160
Дата присоединения: Jul 2022
Сообщения: 10
Спасибо: 38
1 месяцев назад · Jul 14, 2026 5:52 AM
#3

Clear architectural breakdown of Span vs Memory lifetime boundaries.