public sealed class ObjectPool<T> where T : classA bounded, lock-free pool of reusable reference-type instances — string builders, command payload objects, per-frame scratch objects — for the places where an allocation per frame would be an allocation per frame too many.
No guide page documents this yet — the page shows what the code says about itself.
Remarks
The pool is a cache, not a ledger. Nothing tracks what has been rented, and Return is advisory: failing to return an instance costs a future allocation and nothing else, and the pool never grows past its capacity. Returning an instance twice, or using one after returning it, is a bug the pool cannot detect — prefer RentScoped, which cannot get it wrong.
On the shape. The design here is a single lock-free fast slot in front of a fixed array of slots, which is what Roslyn's object pool does. The plan (doc 03) described a thread-local free list with shared overflow; that needs either a ThreadLocal`1 per pool — allocating per thread per pool, and the engine has many pools — or a [ThreadStatic] field, which is per type and so cannot serve two pools of the same type. This achieves the same end, an uncontended fast path with bounded retention, and costs one field.
Fields and properties (1)
public int CapacityHow many instances the pool retains at most.
Methods (5)
public ObjectPool(Func<T> factory, Action<T>? reset = null, int capacity = 32)Creates a pool that builds instances with .
public T Rent()Takes an instance from the pool, or builds one.
public void Return(T instance)Offers an instance back to the pool. Resets it first; drops it on the floor for the GC if the pool is full.
public PooledObject<T> RentScoped()Rents an instance tied to a using scope, so it is returned however the scope ends.
public void Clear()Empties the pool, so the instances it holds can be collected.
Used by (4)
- PooledDictionaryVixen.Core
- PooledObjectVixen.Core
- PoolingTestsVixen.Core.Tests
- SlotVixen.Core