/// <summary>
/// A pool of short-lived items of the same type.
///
/// Items taken from the pool have a lifetime of one frame, after which they are automatically
/// returned to the pool.
///
/// You should NOT hold references to items fetched from this pool across frame bounderies
/// however it is impossible for this class to enforce it...
/// </summary>
public class FramePool<T>
{
public delegate T Create();
public readonly Create HandleCreate;
public delegate void Reset(ref T item);
public readonly Reset HandleReset;
private readonly List<T> _in;
private readonly List<T> _out;
public FramePool(int initialCapacity, Create createMethod, Reset resetMethod)
{
HandleCreate = createMethod;
HandleReset = resetMethod;
_in = new List<T>(initialCapacity);
for (var i = 0; i < initialCapacity; i++)
{
_in.Add(HandleCreate());
}
_out = new List<T>();
}
public T Get()
{
if (_in.Count == 0)
{
_in.Add(HandleCreate());
}
var item = _in.PopLast();
_out.Add(item);
return item;
}
public void EndOfFrame()
{
_in.AddRange(_out);
_out.Clear();
}
}
所以有几种类型的&#39;对象池&#39;
标准类型,调用var obj = pool.Get()
的代码在完成后也需要调用Return(obj)
。
然后就像我在这里的游泳池一样,通过“回归一切”来解决这个问题。在程序中的某个常规点调用的方法。
现在,这不是世界上最安全的类,因为它无法强制调用者停止在帧边界上使用对象。哪个好...... 但也许有人可以想出一个聪明的方法,在C#中,实现一个单帧对象池,可以强制执行“正确的”##用法和/或检测错误&#39;的使用。