Can Span<T> keep managed memory from being garbage collected?

Viewed 349

Span<T> is a ref struct that represents a contiguous region of arbitrary memory. It has an internal field called _pointer of type ByReference<T>, which is .NET's workaround for the lack of by-ref fields in C#/CIL and is handled specially by the JIT and type loader. My question is, because this field is Span<T>'s only reference to the arbitrary memory, can Span<T> still be guaranteed to keep any managed memory it represents alive? For example:

public static Span<byte> GetSpan(int length) => new byte[length];

public static void Method()
{
    var span = GetSpan(1);

    GC.Collect();
    GC.WaitForPendingFinalizers();

    // ...

    span[0] = 0; // Will this always succeed?
}
0 Answers
Related