NAK_CVR_Mods/PropSpawnTweaks/ObjectPool.cs
2024-06-22 01:49:44 -05:00

45 lines
No EOL
974 B
C#

namespace NAK.PropSpawnTweaks;
public class ObjectPool<T>
{
public int Count { get; private set; }
private readonly Queue<T> _available;
private readonly Func<T> _createObjectFunc;
public ObjectPool(int numPreallocated = 0, Func<T> createObjectFunc = null)
{
_available = new Queue<T>();
_createObjectFunc = createObjectFunc;
if (numPreallocated > 0) Give(MakeObject());
}
public T Take()
{
T t;
if (_available.Count > 0)
{
t = _available.Dequeue();
Count--;
}
else
{
t = MakeObject();
}
return t;
}
public void Give(T t)
{
_available.Enqueue(t);
Count++;
}
private T MakeObject()
{
if (_createObjectFunc != null) return _createObjectFunc();
throw new InvalidOperationException("Cannot automatically create new objects without a factory method");
}
}