using System;
using System.Collections.Concurrent;
namespace VocaluxeLib.Utils
{
// Modified version of https://docs.microsoft.com/en-us/dotnet/standard/collections/thread-safe/how-to-create-an-object-pool
///
/// Pool for objects.
///
/// Type of the objects in the pool.
public class CObjectPool
{
private readonly ConcurrentBag _Objects;
private readonly Func _ObjectGenerator;
private readonly int _Poolsize;
///
/// Create a new object pool.
///
/// Function witch generate a new object instance.
/// Number of objects to keep in the pool.
public CObjectPool(Func objectGenerator, int poolSize)
{
if (objectGenerator == null)
{
throw new ArgumentNullException(nameof(objectGenerator));
}
if (poolSize <= 0)
{
throw new ArgumentNullException(nameof(poolSize));
}
_Objects = new ConcurrentBag();
_ObjectGenerator = objectGenerator;
_Poolsize = poolSize;
}
///
/// Get an object (from the pool or a new one).
///
/// An object instance.
public T GetObject()
{
T item;
if (_Objects.TryTake(out item))
{
return item;
}
return _ObjectGenerator();
}
///
/// Put an intance back to the pool.
///
/// The object instance that is given back to the pool.
public void PutObject(T item)
{
if (_Objects.Count < _Poolsize)
{
_Objects.Add(item);
}
else
{
(item as IDisposable)?.Dispose();
}
}
}
}