ArrayPool.cs 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123
  1. using System.Collections.Generic;
  2. namespace IFramework
  3. {
  4. /// <summary>
  5. /// ArrayPoolArg
  6. /// </summary>
  7. public struct ArrayPoolArg : IEventArgs
  8. {
  9. /// <summary>
  10. /// 长度
  11. /// </summary>
  12. public int length;
  13. /// <summary>
  14. ///
  15. /// </summary>
  16. /// <param name="length"></param>
  17. public ArrayPoolArg(int length)
  18. {
  19. this.length = length;
  20. }
  21. }
  22. /// <summary>
  23. /// 数组
  24. /// </summary>
  25. /// <typeparam name="T"></typeparam>
  26. public class ArrayPool<T> : ObjectPool<T[]>
  27. {
  28. private Queue<int> _lengthqueue = new Queue<int>();
  29. /// <summary>
  30. /// 创建
  31. /// </summary>
  32. /// <param name="arg"></param>
  33. /// <returns></returns>
  34. protected override T[] CreateNew(IEventArgs arg)
  35. {
  36. ArrayPoolArg len = (ArrayPoolArg)arg;
  37. return new T[len.length];
  38. }
  39. Queue<T[]> queue = new Queue<T[]>();
  40. /// <summary>
  41. /// 获取
  42. /// </summary>
  43. /// <param name="arg"></param>
  44. /// <returns></returns>
  45. public override T[] Get(IEventArgs arg = null)
  46. {
  47. ArrayPoolArg len = (ArrayPoolArg)arg;
  48. int length = len.length;
  49. lock (para)
  50. {
  51. T[] t;
  52. if (pool.Count > 0 && _lengthqueue.Contains(length))
  53. {
  54. while (_lengthqueue.Peek() != length)
  55. {
  56. _lengthqueue.Dequeue();
  57. queue.Enqueue(pool.Dequeue());
  58. }
  59. t = pool.Dequeue();
  60. while (pool.Count != 0) queue.Enqueue(pool.Dequeue());
  61. int _count = queue.Count;
  62. for (int i = 0; i < _count; i++)
  63. {
  64. var tmp = queue.Dequeue();
  65. int _len = tmp.Length;
  66. _lengthqueue.Enqueue(_len);
  67. pool.Enqueue(tmp);
  68. }
  69. }
  70. else
  71. {
  72. t = CreateNew(arg);
  73. OnCreate(t, arg);
  74. }
  75. OnGet(t, arg);
  76. return t;
  77. }
  78. }
  79. /// <summary>
  80. /// 回收
  81. /// </summary>
  82. /// <param name="t"></param>
  83. /// <param name="arg"></param>
  84. /// <returns></returns>
  85. public override bool Set(T[] t, IEventArgs arg = null)
  86. {
  87. lock (para)
  88. {
  89. if (!pool.Contains(t))
  90. {
  91. if (OnSet(t, arg))
  92. {
  93. int _len = t.Length;
  94. _lengthqueue.Enqueue(_len);
  95. pool.Enqueue(t);
  96. }
  97. return true;
  98. }
  99. else
  100. {
  101. Log.E("Set Err: Exist " + type);
  102. return false;
  103. }
  104. }
  105. }
  106. /// <summary>
  107. /// 释放
  108. /// </summary>
  109. protected override void OnDispose()
  110. {
  111. base.OnDispose();
  112. if (_lengthqueue != null)
  113. {
  114. _lengthqueue.Clear();
  115. }
  116. }
  117. }
  118. }