Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C#

System.Buffers.MemoryPool: practical reference

System.Buffers.MemoryPool: practical reference: MemoryPool<T> rents an IMemoryOwner<T> whose Memory<T> remains owned until Dispose returns the resource.

Version: .NET API; verified on .NET 10.0.14

Syntax

System.Buffers.MemoryPool /* select a documented member or constructor */

MemoryPool rents an IMemoryOwner whose Memory remains owned until Dispose returns the resource.

Use it when a buffer must outlive a Span scope or cross an async boundary without immediate copying.

Do not access Memory after disposing its owner, and do not copy ownership without a clear single responsibility for disposal.

The requested size is a minimum: Rent may return a larger block, while MaximumBufferSize limits supported requests.

The complete program actually uses System.Buffers.MemoryPool; its exact expected stdout is 5.

Examples

using System;
using System.Buffers;
using System.Collections.Concurrent;
using System.Collections.Frozen;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Text.Json.Serialization;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Channels;
using System.Threading.Tasks;
using Number = System.Int32;

using var owner = MemoryPool<byte>.Shared.Rent(4);
owner.Memory.Span[0] = 5;
Console.WriteLine(owner.Memory.Span[0]);

Result

5

The complete program actually uses `System.Buffers.MemoryPool`; its exact expected stdout is `5`.

Sources