WaitableCounter.cs 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  1. using SmartCoalApplication.SystemLayer;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading;
  7. using System.Threading.Tasks;
  8. namespace SmartCoalApplication.Core.Threading
  9. {
  10. public class WaitableCounter
  11. {
  12. public static int MinimumCount
  13. {
  14. get
  15. {
  16. return WaitHandleArray.MinimumCount;
  17. }
  18. }
  19. public static int MaximumCount
  20. {
  21. get
  22. {
  23. return WaitHandleArray.MaximumCount;
  24. }
  25. }
  26. private sealed class CounterToken
  27. : IDisposable
  28. {
  29. private WaitableCounter parent;
  30. private int index;
  31. public int Index
  32. {
  33. get
  34. {
  35. return this.index;
  36. }
  37. }
  38. public CounterToken(WaitableCounter parent, int index)
  39. {
  40. this.parent = parent;
  41. this.index = index;
  42. }
  43. public void Dispose()
  44. {
  45. parent.Release(this);
  46. }
  47. }
  48. private WaitHandleArray freeEvents;
  49. private WaitHandleArray inUseEvents;
  50. private object theLock;
  51. public WaitableCounter(int maxCount)
  52. {
  53. if (maxCount < 1 || maxCount > 64)
  54. {
  55. throw new ArgumentOutOfRangeException("maxCount", "must be between 1 and 64, inclusive");
  56. }
  57. this.freeEvents = new WaitHandleArray(maxCount);
  58. this.inUseEvents = new WaitHandleArray(maxCount);
  59. for (int i = 0; i < maxCount; ++i)
  60. {
  61. this.freeEvents[i] = new ManualResetEvent(true);
  62. this.inUseEvents[i] = new ManualResetEvent(false);
  63. }
  64. this.theLock = new object();
  65. }
  66. private void Release(CounterToken token)
  67. {
  68. ((ManualResetEvent)this.inUseEvents[token.Index]).Reset();
  69. ((ManualResetEvent)this.freeEvents[token.Index]).Set();
  70. }
  71. public IDisposable AcquireToken()
  72. {
  73. lock (this.theLock)
  74. {
  75. int index = WaitForNotFull();
  76. ((ManualResetEvent)this.freeEvents[index]).Reset();
  77. ((ManualResetEvent)this.inUseEvents[index]).Set();
  78. return new CounterToken(this, index);
  79. }
  80. }
  81. public bool IsEmpty()
  82. {
  83. return IsEmpty(0);
  84. }
  85. public bool IsEmpty(uint msTimeout)
  86. {
  87. return freeEvents.AreAllSignaled(msTimeout);
  88. }
  89. public void WaitForEmpty()
  90. {
  91. freeEvents.WaitAll();
  92. }
  93. public int WaitForNotFull()
  94. {
  95. int returnVal = freeEvents.WaitAny();
  96. return returnVal;
  97. }
  98. }
  99. }