ObjectPool.cs 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. using System.Collections.Generic;
  2. using System.Diagnostics;
  3. namespace TBL.CSharp.Utilities
  4. {
  5. /// <summary>
  6. /// 对象池
  7. /// </summary>
  8. public class ObjectPool<T> where T : new()
  9. {
  10. /// <summary>
  11. /// 对象集合
  12. /// </summary>
  13. private readonly Queue<T> _set = new Queue<T>();
  14. /// <summary>
  15. /// 全局对象
  16. /// </summary>
  17. public static readonly ObjectPool<T> Global = new ObjectPool<T>();
  18. /// <summary>
  19. /// 剩余对象计数
  20. /// </summary>
  21. public int RemainCount => _set.Count;
  22. /// <summary>
  23. /// 回收池对象
  24. /// </summary>
  25. public void Recycle(T instance)
  26. {
  27. Debug.Assert(instance != null);
  28. _set.Enqueue(instance);
  29. }
  30. /// <summary>
  31. /// 预分配
  32. /// </summary>
  33. public void Preallocate(int size)
  34. {
  35. for (var i = 0; i < size; i++)
  36. _set.Enqueue(new T());
  37. }
  38. /// <summary>
  39. /// 获取一个池对象
  40. /// <para>注意手动初始化和清理</para>
  41. /// </summary>
  42. public T Use()
  43. {
  44. return _set.Count > 0
  45. ? _set.Dequeue()
  46. : new T();
  47. }
  48. /// <summary>
  49. /// 清空池对象
  50. /// </summary>
  51. public void Clear()
  52. {
  53. _set.Clear();
  54. }
  55. }
  56. }