ListPool.cs 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. using System;
  2. using System.Collections.Generic;
  3. using XGame.Framework.Memory;
  4. namespace XGame.Framework
  5. {
  6. /// <summary>
  7. /// List缓存池
  8. /// * 非线程安全
  9. /// </summary>
  10. public static partial class ListPool
  11. {
  12. static readonly Dictionary<Type, Stack<object>> pool = new();
  13. const int CACHE_LIMIT = 32;
  14. internal static void Initialize()
  15. {
  16. MemoryMonitor.Register(Clear);
  17. }
  18. internal static void Dispose()
  19. {
  20. pool.Clear();
  21. MemoryMonitor.UnRegister(Clear);
  22. }
  23. public static void Clear()
  24. {
  25. pool.Clear();
  26. }
  27. public static List<T> Acquire<T>()
  28. {
  29. Type type = typeof(T);
  30. if (pool.ContainsKey(type))
  31. {
  32. var stack = pool[type];
  33. if (stack.Count > 0)
  34. return stack.Pop() as List<T>;
  35. }
  36. return new List<T>();
  37. }
  38. public static void Recycle<T>(List<T> list)
  39. {
  40. if ( list == null)
  41. {
  42. return;
  43. }
  44. Type type = typeof(T);
  45. if (!pool.TryGetValue(type, out var stack))
  46. {
  47. stack = new Stack<object>();
  48. pool.Add(type, stack);
  49. }
  50. list.Clear();
  51. if (stack.Count >= CACHE_LIMIT)
  52. stack.Clear();
  53. else if (stack.Contains(list))
  54. {
  55. Log.Error($"ObjectPool.Recycle 重复回收, type: {type.FullName}");
  56. return;
  57. }
  58. stack.Push(list);
  59. }
  60. }
  61. }