SemaphoreSlim.cs 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  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. const int spinCount = 10;
  32. const int deepSleepTime = 20;
  33. readonly int max;
  34. int currCount;
  35. bool isDisposed;
  36. EventWaitHandle handle;
  37. public SemaphoreSlim (int initial) : this (initial, int.MaxValue)
  38. {
  39. }
  40. public SemaphoreSlim (int initial, int max)
  41. {
  42. if (initial < 0 || initial > max || max < 0)
  43. throw new ArgumentOutOfRangeException ("The initial argument is negative, initial is greater than max, or max is not positive.");
  44. this.max = max;
  45. this.currCount = initial;
  46. this.handle = new ManualResetEvent (initial == 0);
  47. }
  48. ~SemaphoreSlim ()
  49. {
  50. Dispose(false);
  51. }
  52. public void Dispose ()
  53. {
  54. Dispose(true);
  55. }
  56. protected virtual void Dispose (bool managedRes)
  57. {
  58. isDisposed = true;
  59. }
  60. void CheckState ()
  61. {
  62. if (isDisposed)
  63. throw new ObjectDisposedException ("The SemaphoreSlim has been disposed.");
  64. }
  65. public int CurrentCount {
  66. get {
  67. return currCount;
  68. }
  69. }
  70. public int Release ()
  71. {
  72. return Release(1);
  73. }
  74. public int Release (int releaseCount)
  75. {
  76. CheckState ();
  77. if (releaseCount < 1)
  78. throw new ArgumentOutOfRangeException ("releaseCount", "releaseCount is less than 1");
  79. // As we have to take care of the max limit we resort to CAS
  80. int oldValue, newValue;
  81. do {
  82. oldValue = currCount;
  83. newValue = (currCount + releaseCount);
  84. newValue = newValue > max ? max : newValue;
  85. } while (Interlocked.CompareExchange (ref currCount, newValue, oldValue) != oldValue);
  86. handle.Set ();
  87. return oldValue;
  88. }
  89. public void Wait ()
  90. {
  91. Wait (CancellationToken.None);
  92. }
  93. public bool Wait (TimeSpan ts)
  94. {
  95. return Wait ((int)ts.TotalMilliseconds, CancellationToken.None);
  96. }
  97. public bool Wait (int millisecondsTimeout)
  98. {
  99. return Wait (millisecondsTimeout, CancellationToken.None);
  100. }
  101. public void Wait (CancellationToken token)
  102. {
  103. Wait (-1, token);
  104. }
  105. public bool Wait (TimeSpan ts, CancellationToken token)
  106. {
  107. CheckState();
  108. return Wait ((int)ts.TotalMilliseconds, token);
  109. }
  110. public bool Wait (int millisecondsTimeout, CancellationToken token)
  111. {
  112. CheckState ();
  113. if (millisecondsTimeout < -1)
  114. throw new ArgumentOutOfRangeException ("millisecondsTimeout",
  115. "millisecondsTimeout is a negative number other than -1");
  116. Watch sw = Watch.StartNew ();
  117. Func<bool> stopCondition = () => millisecondsTimeout >= 0 && sw.ElapsedMilliseconds > millisecondsTimeout;
  118. do {
  119. bool shouldWait;
  120. int result;
  121. do {
  122. token.ThrowIfCancellationRequested ();
  123. if (stopCondition ())
  124. return false;
  125. shouldWait = true;
  126. result = currCount;
  127. if (result > 0)
  128. shouldWait = false;
  129. else
  130. break;
  131. } while (Interlocked.CompareExchange (ref currCount, result - 1, result) != result);
  132. if (!shouldWait) {
  133. if (result == 1)
  134. handle.Reset ();
  135. break;
  136. }
  137. SpinWait wait = new SpinWait ();
  138. while (Thread.VolatileRead (ref currCount) <= 0) {
  139. token.ThrowIfCancellationRequested ();
  140. if (stopCondition ())
  141. return false;
  142. if (wait.Count > spinCount)
  143. handle.WaitOne (Math.Min (Math.Max (millisecondsTimeout - (int)sw.ElapsedMilliseconds, 1), deepSleepTime));
  144. else
  145. wait.SpinOnce ();
  146. }
  147. } while (true);
  148. return true;
  149. }
  150. public WaitHandle AvailableWaitHandle {
  151. get {
  152. return handle;
  153. }
  154. }
  155. }
  156. }
  157. #endif