SemaphoreSlim.cs 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  1. // SemaphoreSlim.cs
  2. //
  3. // Copyright (c) 2008 Jérémie "Garuma" Laval
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. //
  23. //
  24. using System;
  25. using System.Diagnostics;
  26. #if NET_4_0
  27. namespace System.Threading
  28. {
  29. public class SemaphoreSlim : IDisposable
  30. {
  31. readonly int max;
  32. int currCount;
  33. bool isDisposed;
  34. ManualResetEvent handle;
  35. public SemaphoreSlim (int initial) : this (initial, int.MaxValue)
  36. {
  37. }
  38. public SemaphoreSlim (int initial, int max)
  39. {
  40. if (initial < 0 || initial > max || max < 0)
  41. throw new ArgumentOutOfRangeException ("The initial argument is negative, initial is greater than max, or max is not positive.");
  42. this.max = max;
  43. this.currCount = initial;
  44. this.handle = new ManualResetEvent (initial == 0);
  45. }
  46. ~SemaphoreSlim ()
  47. {
  48. Dispose(false);
  49. }
  50. public void Dispose ()
  51. {
  52. Dispose(true);
  53. }
  54. protected virtual void Dispose (bool managedRes)
  55. {
  56. isDisposed = true;
  57. }
  58. void CheckState ()
  59. {
  60. if (isDisposed)
  61. throw new ObjectDisposedException ("The SemaphoreSlim has been disposed.");
  62. }
  63. public int CurrentCount {
  64. get {
  65. return currCount;
  66. }
  67. }
  68. public int Release ()
  69. {
  70. return Release(1);
  71. }
  72. public int Release (int releaseCount)
  73. {
  74. CheckState ();
  75. if (releaseCount < 1)
  76. throw new ArgumentOutOfRangeException ("releaseCount", "releaseCount is less than 1");
  77. // As we have to take care of the max limit we resort to CAS
  78. int oldValue, newValue;
  79. do {
  80. oldValue = currCount;
  81. newValue = (currCount + releaseCount);
  82. newValue = newValue > max ? max : newValue;
  83. } while (Interlocked.CompareExchange (ref currCount, newValue, oldValue) != oldValue);
  84. handle.Reset ();
  85. return oldValue;
  86. }
  87. public void Wait ()
  88. {
  89. Wait (CancellationToken.None);
  90. }
  91. public bool Wait (TimeSpan ts)
  92. {
  93. return Wait ((int)ts.TotalMilliseconds, CancellationToken.None);
  94. }
  95. public bool Wait (int millisecondsTimeout)
  96. {
  97. return Wait (millisecondsTimeout, CancellationToken.None);
  98. }
  99. public void Wait (CancellationToken token)
  100. {
  101. Wait (-1, token);
  102. }
  103. public bool Wait (TimeSpan ts, CancellationToken token)
  104. {
  105. CheckState();
  106. return Wait ((int)ts.TotalMilliseconds, token);
  107. }
  108. public bool Wait (int millisecondsTimeout, CancellationToken token)
  109. {
  110. CheckState ();
  111. if (millisecondsTimeout < -1)
  112. throw new ArgumentOutOfRangeException ("millisecondsTimeout",
  113. "millisecondsTimeout is a negative number other than -1");
  114. Watch sw = Watch.StartNew ();
  115. Func<bool> stopCondition =
  116. () => token.IsCancellationRequested || (millisecondsTimeout >= 0 && sw.ElapsedMilliseconds > millisecondsTimeout);
  117. do {
  118. bool shouldWait;
  119. int result;
  120. do {
  121. if (stopCondition ())
  122. return false;
  123. shouldWait = true;
  124. result = currCount;
  125. if (result > 0)
  126. shouldWait = false;
  127. else
  128. break;
  129. } while (Interlocked.CompareExchange (ref currCount, result - 1, result) != result);
  130. if (!shouldWait) {
  131. if (result == 1)
  132. handle.Set ();
  133. break;
  134. }
  135. SpinWait wait = new SpinWait ();
  136. while (Thread.VolatileRead (ref currCount) <= 0) {
  137. if (stopCondition ())
  138. return false;
  139. wait.SpinOnce ();
  140. }
  141. } while (true);
  142. return true;
  143. }
  144. public WaitHandle AvailableWaitHandle {
  145. get {
  146. return handle;
  147. }
  148. }
  149. }
  150. }
  151. #endif