ObjectPool
A simple object pool that reuses instances of a reference type to reduce allocations.
internal sealed class ObjectPool<T> : System.IDisposable where T : classExamples
Section titled “Examples”The following example creates an object pool for a custom reference type.
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); }}Constructors
Section titled “Constructors”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.
public ObjectPool(Func<T> create, Action<T>? onGet = null, Action<T>? onReturn = null, Action<T>? onDispose = null);create
Section titled “create”A factory function to create new instances when the pool is empty.
An optional callback invoked when an object is retrieved from the pool.
onReturn
Section titled “onReturn”An optional callback invoked when an object is returned to the pool.
onDispose
Section titled “onDispose”An optional callback invoked for each remaining object when the pool is disposed.
Methods
Section titled “Methods”Dispose()
Section titled “Dispose()”Disposes the pool, invoking the onDispose callback for each remaining object.
public void Dispose();Retrieves an object from the pool. Creates a new instance if the pool is empty.
public T Get();Returns
Section titled “Returns”An object from the pool.
Get(out T)
Section titled “Get(out T)”Retrieves an object from the pool and wraps it in a disposable scope that returns it automatically.
public PoolScope<T> Get(out T item);When this method returns, contains the object retrieved from the pool.
Returns
Section titled “Returns”A disposable scope that returns the object to the pool when disposed.
Return(T)
Section titled “Return(T)”Returns an object to the pool.
public void Return(T value);The object to return to the pool.