1 // ManualResetEventSlim.cs
4 // Marek Safar <marek.safar@gmail.com>
6 // Copyright (c) 2008 Jérémie "Garuma" Laval
7 // Copyright 2011 Xamarin Inc (http://www.xamarin.com).
9 // Permission is hereby granted, free of charge, to any person obtaining a copy
10 // of this software and associated documentation files (the "Software"), to deal
11 // in the Software without restriction, including without limitation the rights
12 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13 // copies of the Software, and to permit persons to whom the Software is
14 // furnished to do so, subject to the following conditions:
16 // The above copyright notice and this permission notice shall be included in
17 // all copies or substantial portions of the Software.
19 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
31 namespace System.Threading
33 [System.Diagnostics.DebuggerDisplayAttribute ("Set = {IsSet}")]
34 public class ManualResetEventSlim : IDisposable
36 readonly int spinCount;
38 ManualResetEvent handle;
39 internal AtomicBooleanValue disposed;
43 public ManualResetEventSlim ()
48 public ManualResetEventSlim (bool initialState)
49 : this (initialState, 10)
53 public ManualResetEventSlim (bool initialState, int spinCount)
55 if (spinCount < 0 || spinCount > 2047)
56 throw new ArgumentOutOfRangeException ("spinCount");
58 this.state = initialState ? 1 : 0;
59 this.spinCount = spinCount;
64 return (state & 1) == 1;
68 public int SpinCount {
78 var stamp = UpdateStateWithOp (false);
80 CommitChangeToHandle (stamp);
85 var stamp = UpdateStateWithOp (true);
87 CommitChangeToHandle (stamp);
90 long UpdateStateWithOp (bool set)
92 int oldValue, newValue;
95 newValue = (int)(((oldValue >> 1) + 1) << 1) | (set ? 1 : 0);
96 } while (Interlocked.CompareExchange (ref state, newValue, oldValue) != oldValue);
100 void CommitChangeToHandle (long stamp)
102 Interlocked.Increment (ref used);
103 var tmpHandle = handle;
104 if (tmpHandle != null) {
105 // First in all case we carry the operation we were called for
106 if ((stamp & 1) == 1)
111 /* Then what may happen is that the two suboperations (state change and handle change)
112 * overlapped with others. In our case it doesn't matter if the two suboperations aren't
113 * executed together at the same time, the only thing we have to make sure of is that both
114 * state and handle are synchronized on the last visible state change.
116 * For instance if S is state change and H is handle change, for 3 concurrent operations
117 * we may have the following serialized timeline: S1 S2 H2 S3 H3 H1
118 * Which is perfectly fine (all S were converted to H at some stage) but in that case
119 * we have a mismatch between S and H at the end because the last operations done were
120 * S3/H1. We thus need to repeat H3 to get to the desired final state.
124 currentState = state;
125 if (currentState != stamp && (stamp & 1) != (currentState & 1)) {
126 if ((currentState & 1) == 1)
131 } while (currentState != state);
133 Interlocked.Decrement (ref used);
138 Wait (CancellationToken.None);
141 public bool Wait (int millisecondsTimeout)
143 return Wait (millisecondsTimeout, CancellationToken.None);
146 public bool Wait (TimeSpan timeout)
148 return Wait (CheckTimeout (timeout), CancellationToken.None);
151 public void Wait (CancellationToken cancellationToken)
153 Wait (Timeout.Infinite, cancellationToken);
156 public bool Wait (int millisecondsTimeout, CancellationToken cancellationToken)
158 if (millisecondsTimeout < -1)
159 throw new ArgumentOutOfRangeException ("millisecondsTimeout");
164 SpinWait wait = new SpinWait ();
167 if (wait.Count < spinCount) {
175 cancellationToken.ThrowIfCancellationRequested ();
180 WaitHandle handle = WaitHandle;
182 if (cancellationToken.CanBeCanceled) {
183 var result = WaitHandle.WaitAny (new[] { handle, cancellationToken.WaitHandle }, millisecondsTimeout, false);
185 throw new OperationCanceledException (cancellationToken);
186 if (result == WaitHandle.WaitTimeout)
189 if (!handle.WaitOne (millisecondsTimeout, false))
197 public bool Wait (TimeSpan timeout, CancellationToken cancellationToken)
199 return Wait (CheckTimeout (timeout), cancellationToken);
202 public WaitHandle WaitHandle {
210 var mre = new ManualResetEvent (IsSet);
211 if (Interlocked.CompareExchange (ref handle, mre, null) == null) {
213 // Ensure the Set has not ran meantime
215 if (isSet != IsSet) {
224 // Release the event when other thread was faster
233 public void Dispose ()
238 protected virtual void Dispose (bool disposing)
240 if (!disposed.TryRelaxedSet ())
243 if (handle != null) {
244 var tmpHandle = Interlocked.Exchange (ref handle, null);
246 // A tiny wait (just a few cycles normally) before releasing
247 SpinWait wait = new SpinWait ();
251 tmpHandle.Dispose ();
255 void ThrowIfDisposed ()
258 throw new ObjectDisposedException ("ManualResetEventSlim");
261 static int CheckTimeout (TimeSpan timeout)
264 return checked ((int)timeout.TotalMilliseconds);
265 } catch (System.OverflowException) {
266 throw new ArgumentOutOfRangeException ("timeout");