123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263 |
- using System.Collections.Generic;
- using System.Diagnostics;
- namespace TBL.CSharp.Utilities
- {
- /// <summary>
- /// 对象池
- /// </summary>
- public class ObjectPool<T> where T : new()
- {
- /// <summary>
- /// 对象集合
- /// </summary>
- private readonly Queue<T> _set = new Queue<T>();
- /// <summary>
- /// 全局对象
- /// </summary>
- public static readonly ObjectPool<T> Global = new ObjectPool<T>();
- /// <summary>
- /// 剩余对象计数
- /// </summary>
- public int RemainCount => _set.Count;
- /// <summary>
- /// 回收池对象
- /// </summary>
- public void Recycle(T instance)
- {
- Debug.Assert(instance != null);
- _set.Enqueue(instance);
- }
- /// <summary>
- /// 预分配
- /// </summary>
- public void Preallocate(int size)
- {
- for (var i = 0; i < size; i++)
- _set.Enqueue(new T());
- }
- /// <summary>
- /// 获取一个池对象
- /// <para>注意手动初始化和清理</para>
- /// </summary>
- public T Use()
- {
- return _set.Count > 0
- ? _set.Dequeue()
- : new T();
- }
- /// <summary>
- /// 清空池对象
- /// </summary>
- public void Clear()
- {
- _set.Clear();
- }
- }
- }
|