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 [System.Diagnostics.DebuggerDisplayAttribute ("Current Count = {currCount}")]
32 public class SemaphoreSlim : IDisposable
34 const int spinCount = 10;
35 const int deepSleepTime = 20;
37 readonly int maxCount;
41 EventWaitHandle handle;
43 public SemaphoreSlim (int initialCount) : this (initialCount, int.MaxValue)
47 public SemaphoreSlim (int initialCount, int maxCount)
49 if (initialCount < 0 || initialCount > maxCount || maxCount < 0)
50 throw new ArgumentOutOfRangeException ("The initialCount argument is negative, initialCount is greater than maxCount, or maxCount is not positive.");
52 this.maxCount = maxCount;
53 this.currCount = initialCount;
54 this.handle = new ManualResetEvent (initialCount == 0);
62 public void Dispose ()
67 protected virtual void Dispose (bool disposing)
75 throw new ObjectDisposedException ("The SemaphoreSlim has been disposed.");
78 public int CurrentCount {
89 public int Release (int releaseCount)
93 throw new ArgumentOutOfRangeException ("releaseCount", "releaseCount is less than 1");
95 // As we have to take care of the max limit we resort to CAS
96 int oldValue, newValue;
99 newValue = (currCount + releaseCount);
100 newValue = newValue > maxCount ? maxCount : newValue;
101 } while (Interlocked.CompareExchange (ref currCount, newValue, oldValue) != oldValue);
110 Wait (CancellationToken.None);
113 public bool Wait (TimeSpan timeout)
115 return Wait ((int)timeout.TotalMilliseconds, CancellationToken.None);
118 public bool Wait (int millisecondsTimeout)
120 return Wait (millisecondsTimeout, CancellationToken.None);
123 public void Wait (CancellationToken cancellationToken)
125 Wait (-1, cancellationToken);
128 public bool Wait (TimeSpan timeout, CancellationToken cancellationToken)
131 return Wait ((int)timeout.TotalMilliseconds, cancellationToken);
134 public bool Wait (int millisecondsTimeout, CancellationToken cancellationToken)
137 if (millisecondsTimeout < -1)
138 throw new ArgumentOutOfRangeException ("millisecondsTimeout",
139 "millisecondsTimeout is a negative number other than -1");
141 Watch sw = Watch.StartNew ();
143 Func<bool> stopCondition = () => millisecondsTimeout >= 0 && sw.ElapsedMilliseconds > millisecondsTimeout;
150 cancellationToken.ThrowIfCancellationRequested ();
151 if (stopCondition ())
161 } while (Interlocked.CompareExchange (ref currCount, result - 1, result) != result);
169 SpinWait wait = new SpinWait ();
171 while (Thread.VolatileRead (ref currCount) <= 0) {
172 cancellationToken.ThrowIfCancellationRequested ();
173 if (stopCondition ())
176 if (wait.Count > spinCount)
177 handle.WaitOne (Math.Min (Math.Max (millisecondsTimeout - (int)sw.ElapsedMilliseconds, 1), deepSleepTime));
186 public WaitHandle AvailableWaitHandle {