Class ObjectPool<T>
Generic implementation of object pooling pattern with predefined pool size limit. The main purpose is that a limited number of frequently used objects can be kept in the pool for further recycling.
Namespace: System.Memory
Assembly: Nuqleon.Memory.dll
Syntax
public class ObjectPool<T> : ObjectPoolBase<T>, IObjectPool<T>, IObjectPoolAllocateFree<T>, IObjectPoolNew<T> where T : class
Type Parameters
Name | Description |
---|---|
T | Type of the elements stored in the pool. |
Remarks
1) It is not the goal to keep all returned objects. The pool is not meant for storage. If there is no space in the pool, extra returned objects will be dropped. 2) It is implied that if object was obtained from a pool, the caller will return it back in a relatively short time. Keeping objects checked out for long durations is ok, but reduces usefulness of pooling. Just new up your own if that's your intended object usage. 3) Not returning objects to the pool in not detrimental to the pool's work, but is a bad practice.
Rationale: If there is no intent for reusing the object, do not use pool - just use "new".
Constructors
ObjectPool(Func<T>)
Creates a new object pool using the specified factory to create new object instances.
Declaration
public ObjectPool(Func<T> factory)
Parameters
Type | Name | Description |
---|---|---|
System.Func<T> | factory | Factory delegate used to create new object instances. |
Exceptions
Type | Condition |
---|---|
System.ArgumentNullException | Thrown if |
ObjectPool(Func<T>, Int32)
Creates a new object pool using the specified factory to create new object instances and using the specified pool size.
Declaration
public ObjectPool(Func<T> factory, int size)
Parameters
Type | Name | Description |
---|---|---|
System.Func<T> | factory | Factory delegate used to create new object instances. |
System.Int32 | size | Number of object instances to keep in the pool. |
Exceptions
Type | Condition |
---|---|
System.ArgumentNullException | Thrown if |
Methods
CreateInstance()
Creates an instance of a pooled object.
Declaration
protected override T CreateInstance()
Returns
Type | Description |
---|---|
T | Newly created pooled object instance. |