Skip to content

ObjectPool

A simple object pool that reuses instances of a reference type to reduce allocations.

C# Signature
internal sealed class ObjectPool<T> : System.IDisposable where T : class

The following example creates an object pool for a custom reference type.

C#
using System;
using Hertzole.SourceGen;
public sealed class Buffer
{
public byte[] Data = new byte[1024];
}
public static class BufferPooling
{
public static void Use()
{
// The pool can be disposed to invoke onDispose for the remaining objects.
using ObjectPool<Buffer> pool = new ObjectPool<Buffer>(create: () => new Buffer(), onReturn: buffer => buffer.Data.AsSpan().Clear());
Buffer buffer = pool.Get();
// Do work with the buffer...
pool.Return(buffer);
}
}

ObjectPool(Func<T>, Action<T>?, Action<T>?, Action<T>?)

Section titled “ObjectPool(Func<T>, Action<T>?, Action<T>?, Action<T>?)”

Creates a new object pool.

C# Signature
public ObjectPool(Func<T> create, Action<T>? onGet = null, Action<T>? onReturn = null, Action<T>? onDispose = null);

A factory function to create new instances when the pool is empty.

An optional callback invoked when an object is retrieved from the pool.

An optional callback invoked when an object is returned to the pool.

An optional callback invoked for each remaining object when the pool is disposed.

Disposes the pool, invoking the onDispose callback for each remaining object.

C# Signature
public void Dispose();

Retrieves an object from the pool. Creates a new instance if the pool is empty.

C# Signature
public T Get();

An object from the pool.

Retrieves an object from the pool and wraps it in a disposable scope that returns it automatically.

C# Signature
public PoolScope<T> Get(out T item);

When this method returns, contains the object retrieved from the pool.

A disposable scope that returns the object to the pool when disposed.

Returns an object to the pool.

C# Signature
public void Return(T value);

The object to return to the pool.