Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C#

IMemoryOwner<T> — ownership of a memory buffer

IMemoryOwner<T> expresses responsibility for a buffer's lifetime. Its Memory property exposes the contents as Memory<T>, while the inherited Dispose ends the owner's use of the resource.

Version: .NET 10; repository net10.0 and LangVersion=preview; feature versions require per-entry verification

Syntax

public interface IMemoryOwner<T> : IDisposable
{
    Memory<T> Memory { get; }
}

IMemoryOwner<T> in System.Buffers represents the owner of a buffer of elements of type T. It is available in .NET 10. A buffer has one owner at a time, although it may have multiple consumers. Ownership means responsibility for the resource's lifetime, not exclusive access to its data.

The IMemoryOwner<T>.Memory property has type Memory<T> and only a get accessor. This does not make the elements immutable: they can be modified through owner.Memory.Span. Passing a Memory<T> view to other code does not itself transfer ownership or extend the buffer's lifetime.

The interface inherits IDisposable.Dispose. Call Dispose() only after all consumers, including asynchronous operations, have finished; afterward, do not use the buffer or retained views. An implementation may, for example, return memory to a pool. After transferring ownership, the previous owner should neither use nor dispose of the buffer; the new owner takes that responsibility.

The example uses MemoryPool<int>.Shared.Rent(3), which provides at least three elements, not necessarily exactly three. Slice(0, 3) selects the portion in use, and the code writes every element it reads. The using block calls Dispose() even if an exception occurs. The expected output is 60.

Examples

using System;
using System.Buffers;

internal static class Program
{
    private static void Main()
    {
        using (IMemoryOwner<int> owner = MemoryPool<int>.Shared.Rent(3))
        {
            Memory<int> memory = owner.Memory.Slice(0, 3);
            Span<int> span = memory.Span;
            span[0] = 10;
            span[1] = 20;
            span[2] = 30;

            Console.WriteLine(span[0] + span[1] + span[2]);
        }
    }
}

Result

60

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources