SynchronizedDisposablePool.cs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. //------------------------------------------------------------
  2. // Copyright (c) Microsoft Corporation. All rights reserved.
  3. //------------------------------------------------------------
  4. namespace System.ServiceModel
  5. {
  6. using System.Collections.Generic;
  7. using System.Threading;
  8. class SynchronizedDisposablePool<T> where T : class, IDisposable
  9. {
  10. List<T> items;
  11. int maxCount;
  12. bool disposed;
  13. public SynchronizedDisposablePool(int maxCount)
  14. {
  15. this.items = new List<T>();
  16. this.maxCount = maxCount;
  17. }
  18. object ThisLock
  19. {
  20. get { return this; }
  21. }
  22. public void Dispose()
  23. {
  24. T[] items;
  25. lock (ThisLock)
  26. {
  27. if (!disposed)
  28. {
  29. disposed = true;
  30. if (this.items.Count > 0)
  31. {
  32. items = new T[this.items.Count];
  33. this.items.CopyTo(items, 0);
  34. this.items.Clear();
  35. }
  36. else
  37. {
  38. items = null;
  39. }
  40. }
  41. else
  42. {
  43. items = null;
  44. }
  45. }
  46. if (items != null)
  47. {
  48. for (int i = 0; i < items.Length; i++)
  49. {
  50. items[i].Dispose();
  51. }
  52. }
  53. }
  54. public bool Return(T value)
  55. {
  56. if (!disposed && this.items.Count < this.maxCount)
  57. {
  58. lock (ThisLock)
  59. {
  60. if (!disposed && this.items.Count < this.maxCount)
  61. {
  62. this.items.Add(value);
  63. return true;
  64. }
  65. }
  66. }
  67. return false;
  68. }
  69. public T Take()
  70. {
  71. if (!disposed && this.items.Count > 0)
  72. {
  73. lock (ThisLock)
  74. {
  75. if (!disposed && this.items.Count > 0)
  76. {
  77. int index = this.items.Count - 1;
  78. T item = this.items[index];
  79. this.items.RemoveAt(index);
  80. return item;
  81. }
  82. }
  83. }
  84. return null;
  85. }
  86. }
  87. }