In .NET, what does IMemoryOwner<T> from MemoryPool<T>.Shared.Rent add over a raw ArrayPool<T> rental, and who must dispose it?
answer
- ownership as an object
- Dispose gives the array back
- a parameter of this type takes ownership
- dispose or transfer, never both
basics
~10 sIMemoryOwner<T> turns ownership into an object: whoever holds it must either call Dispose, which returns the pooled array, or hand it on and stop using it. Consumers receive only Memory<T>, which carries no ownership.
solid answer
~40 s`MemoryPool<T>.Shared.Rent(int minBufferSize = -1)` returns an `IMemoryOwner<T>`, an `IDisposable` with a single `Memory<T> Memory` property. On .NET 10 it wraps an array rented from `ArrayPool<T>.Shared`, so `Rent(1000)` gives a 1024-element `Memory`, and `Dispose` returns that array once; a second `Dispose` does nothing and reading `Memory` afterwards throws `ObjectDisposedException`. The usage guidelines make it an ownership token: whoever holds it must dispose it or transfer it, never both; a method with an `IMemoryOwner<T>` parameter accepts ownership; a constructor that takes one belongs on an `IDisposable` type. Code that only receives `Memory<T>` is a consumer and never releases anything. The price is one owner object per `Rent`, so a raw rental with `try`/`finally` stays the better fit when rent and return sit in one method.
code
csharp · 14 linesusing System.Buffers;
IMemoryOwner<byte> owner = MemoryPool<byte>.Shared.Rent(1000);
Console.WriteLine($"Memory.Length = {owner.Memory.Length}");
IMemoryOwner<byte> dflt = MemoryPool<byte>.Shared.Rent();
Console.WriteLine($"default Rent() length = {dflt.Memory.Length}");
dflt.Dispose();
Console.WriteLine($"MaxBufferSize = {MemoryPool<byte>.Shared.MaxBufferSize}");
Memory<byte> kept = owner.Memory;
owner.Dispose();
owner.Dispose(); // second Dispose is a no-op
try { _ = owner.Memory; }
catch (ObjectDisposedException e) { Console.WriteLine(e.GetType().Name); }
Console.WriteLine($"kept.Length still {kept.Length}: the Memory<byte> copy is not invalidated");go deeper
Recall that IMemoryOwner<T> is disposable, that Dispose gives the buffer back, and that its Memory can be longer than you asked for.
Explain owner, consumer and lease, and why a Memory<T> parameter never implies responsibility for releasing the buffer.
Design the hand-off: transfer the owner into a disposable message, slice to the stored length, and make sure exactly one component disposes it.
Decide where an owner object is worth its allocation, at component boundaries, and where plain rent-and-return in one method stays the rule.
## Ownership, consumption and lease The .NET Memory<T> usage guidelines describe every buffer with three ideas: - **Owner**: the one component responsible for the buffer's lifetime, including releasing it. Every buffer has exactly one owner at a time, and ownership can be transferred. - **Consumer**: a component allowed to read, and perhaps write, the buffer. There is one consumer at a time unless something external synchronises them. - **Lease**: how long a consumer may use the buffer, for example until a method returns or until the `Task` it returned completes. A raw `ArrayPool<T>` rental has no object that represents the owner: the `byte[]` is the buffer, the view and the thing you must return, all at once. `IMemoryOwner<T>` separates them. ## The two shapes side by side `IMemoryOwner<T>` is a tiny interface in `System.Buffers`: it extends `IDisposable` and has one property, `Memory<T> Memory { get; }`. `MemoryPool<T>.Shared.Rent(int minBufferSize = -1)` returns one. | | Raw `ArrayPool<T>.Shared` rental | `IMemoryOwner<T>` from `MemoryPool<T>.Shared` | |---|---|---| | What the owner holds | a `T[]` | an `IMemoryOwner<T>` object | | Release | `Return(array)`, exactly once | `Dispose()` | | Releasing twice | silently stores the array twice | second `Dispose` does nothing | | Reading after release | still an ordinary array | `owner.Memory` throws `ObjectDisposedException` | | Length | rounded up to a bucket | the same: on .NET 10 `Rent(1000)` gives `Memory.Length` 1024 | | Extra cost | none | one small owner object per `Rent` | On .NET 10, `MemoryPool<T>.Shared` is built on `ArrayPool<T>.Shared`: each `Rent` allocates a small wrapper that rents an array, and its `Dispose` returns that array once and forgets it. `Rent()` with no argument asks for about 4 KB (4096 elements for `byte`). ## Transferring ownership The guidelines turn the interface into rules an API can express in its signature: 1. **Holding an `IMemoryOwner<T>` means you must dispose it or transfer it, but not both.** Failing to dispose can leak unmanaged memory or degrade performance, depending on what backs it. 2. **An `IMemoryOwner<T>` parameter accepts ownership.** The caller must stop using the instance once the call completes. 3. **A constructor that accepts `IMemoryOwner<T>` should belong to a type that implements `IDisposable`**, whose `Dispose` disposes the owner. 4. **A `Memory<T>` parameter makes the method a consumer only.** It may use the memory during its lease and never releases it. In the upload service, a reader rents an owner per chunk, fills it, and hands the owner to a forwarding stage inside a small disposable message type; the forwarder disposes the message after it has sent the bytes. The reader never touches that chunk again. The message is where the real length lives: ```csharp sealed class Chunk(IMemoryOwner<byte> owner, int length) : IDisposable { public ReadOnlyMemory<byte> Data => owner.Memory[..length]; public void Dispose() => owner.Dispose(); } ``` Exposing `ReadOnlyMemory<byte>` tells the forwarder it may read but not write, and exposing only `Data`, never the owner, keeps a second component from disposing it. If a stage fails before it can pass the chunk on, it disposes the chunk itself; ownership always sits with exactly one stage. ## Limits worth knowing - **Disposing does not revoke views.** A `Memory<byte>` copied out of `owner.Memory` before `Dispose` still points at the array, which is now back in the pool. Only the `Memory` property checks for disposal. - **Slice to the real length.** Because the memory can be longer than requested, store the count with the owner and expose `owner.Memory[..length]`. - **`MemoryPool<T>.Shared` itself is never disposed by your code.** Its `Dispose` is a no-op for the shared instance. - **It costs an object.** When rent and return happen inside one method, a raw `ArrayPool<T>` rental with `try`/`finally` is simpler and allocates nothing extra; the owner object pays for itself when the buffer crosses a component boundary. ## Why interviewers ask it The question separates people who have used pooling from people who have run it. A candidate who says "`IMemoryOwner<T>` is just `ArrayPool` with `using`" has the mechanics; one who explains that the type exists so that ownership transfer is visible in a method signature, and that `Memory<T>` deliberately carries no ownership, has the design.
- Why should a type whose constructor accepts IMemoryOwner<T> implement IDisposable?Because accepting the owner accepts ownership, and the guidelines say the owner must eventually be disposed or passed on. The type holds the buffer for its lifetime, so its own `Dispose` is the natural place to dispose the owner, and its users get the familiar `using` contract.
- After Dispose, can a Memory<T> obtained earlier still be used?It compiles and runs, which is the danger. The copied `Memory<T>` still points at the array that `Dispose` returned to the pool, so it may read or overwrite another renter's data. Only the owner's `Memory` property checks for disposal.
- When is a raw ArrayPool<T> rental the better choice?When rent and return happen in the same method, synchronous or async. A `try`/`finally` with `Rent` and `Return` allocates nothing extra and keeps ownership obvious. `IMemoryOwner<T>` earns its per-rental object when the buffer must move to another component.
An IMemoryOwner<T> is the key to a rental car: whoever holds the key returns the car, and handing the key over hands over that duty. A passenger, like code given only a Memory<T>, may ride along but never returns the car, and must not still be inside once it is returned.
- Disposing the IMemoryOwner<T> invalidates every Memory<T> taken from it.
- A method that takes Memory<T> becomes responsible for releasing it.
- MemoryPool<T>.Shared.Rent(1000).Memory is exactly 1000 elements long.
- Both producer and consumer should dispose the owner, to be safe.
- Your code must dispose MemoryPool<T>.Shared when the app shuts down.
Assumes .NET 10; the ownership rules come from the Memory<T> usage guidelines, while the 1024 rounding, idempotent Dispose and ObjectDisposedException were read from the .NET 10 source.