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;
28 using System.Threading.Tasks;
32 namespace System.Threading
34 [System.Diagnostics.DebuggerDisplayAttribute ("Current Count = {currCount}")]
35 public class SemaphoreSlim : IDisposable
37 const int spinCount = 10;
38 const int deepSleepTime = 20;
40 readonly int maxCount;
44 EventWaitHandle handle;
46 public SemaphoreSlim (int initialCount) : this (initialCount, int.MaxValue)
50 public SemaphoreSlim (int initialCount, int maxCount)
52 if (initialCount < 0 || initialCount > maxCount || maxCount < 0)
53 throw new ArgumentOutOfRangeException ("The initialCount argument is negative, initialCount is greater than maxCount, or maxCount is not positive.");
55 this.maxCount = maxCount;
56 this.currCount = initialCount;
57 this.handle = new ManualResetEvent (initialCount > 0);
60 public void Dispose ()
65 protected virtual void Dispose (bool disposing)
73 throw new ObjectDisposedException ("The SemaphoreSlim has been disposed.");
76 public int CurrentCount {
87 public int Release (int releaseCount)
91 throw new ArgumentOutOfRangeException ("releaseCount", "releaseCount is less than 1");
93 // As we have to take care of the max limit we resort to CAS
94 int oldValue, newValue;
97 newValue = (currCount + releaseCount);
98 newValue = newValue > maxCount ? maxCount : newValue;
99 } while (Interlocked.CompareExchange (ref currCount, newValue, oldValue) != oldValue);
108 Wait (CancellationToken.None);
111 public bool Wait (TimeSpan timeout)
113 return Wait ((int)timeout.TotalMilliseconds, CancellationToken.None);
116 public bool Wait (int millisecondsTimeout)
118 return Wait (millisecondsTimeout, CancellationToken.None);
121 public void Wait (CancellationToken cancellationToken)
123 Wait (-1, cancellationToken);
126 public bool Wait (TimeSpan timeout, CancellationToken cancellationToken)
129 return Wait ((int)timeout.TotalMilliseconds, cancellationToken);
132 public bool Wait (int millisecondsTimeout, CancellationToken cancellationToken)
135 if (millisecondsTimeout < -1)
136 throw new ArgumentOutOfRangeException ("millisecondsTimeout",
137 "millisecondsTimeout is a negative number other than -1");
139 Watch sw = Watch.StartNew ();
141 Func<bool> stopCondition = () => millisecondsTimeout >= 0 && sw.ElapsedMilliseconds > millisecondsTimeout;
148 cancellationToken.ThrowIfCancellationRequested ();
149 if (stopCondition ())
159 } while (Interlocked.CompareExchange (ref currCount, result - 1, result) != result);
167 SpinWait wait = new SpinWait ();
169 while (Volatile.Read (ref currCount) <= 0) {
170 cancellationToken.ThrowIfCancellationRequested ();
171 if (stopCondition ())
174 if (wait.Count > spinCount) {
175 int timeout = millisecondsTimeout < 0 ? deepSleepTime :
176 Math.Min (Math.Max (millisecondsTimeout - (int)sw.ElapsedMilliseconds, 1), deepSleepTime);
177 handle.WaitOne (timeout);
186 public WaitHandle AvailableWaitHandle {
193 public Task WaitAsync ()
195 return Task.Factory.StartNew (() => Wait ());
198 public Task WaitAsync (CancellationToken cancellationToken)
200 return Task.Factory.StartNew (() => Wait (cancellationToken), cancellationToken);
203 public Task<bool> WaitAsync (int millisecondsTimeout)
205 return Task.Factory.StartNew (() => Wait (millisecondsTimeout));
208 public Task<bool> WaitAsync (TimeSpan timeout)
210 return Task.Factory.StartNew (() => Wait (timeout));
213 public Task<bool> WaitAsync (int millisecondsTimeout, CancellationToken cancellationToken)
215 return Task.Factory.StartNew (() => Wait (millisecondsTimeout, cancellationToken), cancellationToken);
218 public Task<bool> WaitAsync (TimeSpan timeout, CancellationToken cancellationToken)
220 return Task.Factory.StartNew (() => Wait (timeout, cancellationToken), cancellationToken);