3 // Copyright (c) 2008 Jérémie "Garuma" Laval
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:
12 // The above copyright notice and this permission notice shall be included in
13 // all copies or substantial portions of the Software.
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
26 using System.Diagnostics;
29 namespace System.Threading
31 public class SemaphoreSlim : IDisposable
33 const int spinCount = 10;
34 const int deepSleepTime = 20;
40 EventWaitHandle handle;
42 public SemaphoreSlim (int initial) : this (initial, int.MaxValue)
46 public SemaphoreSlim (int initial, int max)
48 if (initial < 0 || initial > max || max < 0)
49 throw new ArgumentOutOfRangeException ("The initial argument is negative, initial is greater than max, or max is not positive.");
52 this.currCount = initial;
53 this.handle = new ManualResetEvent (initial == 0);
61 public void Dispose ()
66 protected virtual void Dispose (bool managedRes)
74 throw new ObjectDisposedException ("The SemaphoreSlim has been disposed.");
77 public int CurrentCount {
88 public int Release (int releaseCount)
92 throw new ArgumentOutOfRangeException ("releaseCount", "releaseCount is less than 1");
94 // As we have to take care of the max limit we resort to CAS
95 int oldValue, newValue;
98 newValue = (currCount + releaseCount);
99 newValue = newValue > max ? max : newValue;
100 } while (Interlocked.CompareExchange (ref currCount, newValue, oldValue) != oldValue);
109 Wait (CancellationToken.None);
112 public bool Wait (TimeSpan ts)
114 return Wait ((int)ts.TotalMilliseconds, CancellationToken.None);
117 public bool Wait (int millisecondsTimeout)
119 return Wait (millisecondsTimeout, CancellationToken.None);
122 public void Wait (CancellationToken token)
127 public bool Wait (TimeSpan ts, CancellationToken token)
130 return Wait ((int)ts.TotalMilliseconds, token);
133 public bool Wait (int millisecondsTimeout, CancellationToken token)
136 if (millisecondsTimeout < -1)
137 throw new ArgumentOutOfRangeException ("millisecondsTimeout",
138 "millisecondsTimeout is a negative number other than -1");
140 Watch sw = Watch.StartNew ();
142 Func<bool> stopCondition = () => millisecondsTimeout >= 0 && sw.ElapsedMilliseconds > millisecondsTimeout;
149 token.ThrowIfCancellationRequested ();
150 if (stopCondition ())
160 } while (Interlocked.CompareExchange (ref currCount, result - 1, result) != result);
168 SpinWait wait = new SpinWait ();
170 while (Thread.VolatileRead (ref currCount) <= 0) {
171 token.ThrowIfCancellationRequested ();
172 if (stopCondition ())
175 if (wait.Count > spinCount)
176 handle.WaitOne (Math.Min (Math.Max (millisecondsTimeout - (int)sw.ElapsedMilliseconds, 1), deepSleepTime));
185 public WaitHandle AvailableWaitHandle {