feat: added basic pool helper
This commit is contained in:
parent
2054ae3a35
commit
40735c713a
33
Engine.Core/Helpers/Pool.cs
Normal file
33
Engine.Core/Helpers/Pool.cs
Normal file
@ -0,0 +1,33 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace Syntriax.Engine.Core;
|
||||
|
||||
public class Pool<T>
|
||||
{
|
||||
private readonly Func<T> factory;
|
||||
private readonly Queue<T> queue = new();
|
||||
|
||||
public T Get()
|
||||
{
|
||||
if (queue.TryDequeue(out T? result))
|
||||
return result;
|
||||
|
||||
return factory();
|
||||
}
|
||||
|
||||
public void Return(T item)
|
||||
{
|
||||
if (queue.Contains(item))
|
||||
return;
|
||||
|
||||
queue.Enqueue(item);
|
||||
}
|
||||
|
||||
public Pool(Func<T> factory, int initialCapacity = 1)
|
||||
{
|
||||
this.factory = factory;
|
||||
for (int i = 0; i < initialCapacity; i++)
|
||||
queue.Enqueue(factory());
|
||||
}
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user