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
30 namespace System.Threading
32 [System.Diagnostics.DebuggerDisplayAttribute ("Set = {IsSet}")]
33 public class ManualResetEventSlim : IDisposable
35 readonly int spinCount;
37 ManualResetEvent handle;
38 internal AtomicBooleanValue disposed;
42 public ManualResetEventSlim ()
47 public ManualResetEventSlim (bool initialState)
48 : this (initialState, 10)
52 public ManualResetEventSlim (bool initialState, int spinCount)
54 if (spinCount < 0 || spinCount > 2047)
55 throw new ArgumentOutOfRangeException ("spinCount");
57 this.state = initialState ? 1 : 0;
58 this.spinCount = spinCount;
63 return (state & 1) == 1;
67 public int SpinCount {
77 var stamp = UpdateStateWithOp (false);
79 CommitChangeToHandle (stamp);
84 var stamp = UpdateStateWithOp (true);
86 CommitChangeToHandle (stamp);
89 long UpdateStateWithOp (bool set)
91 int oldValue, newValue;
94 newValue = (int)(((oldValue >> 1) + 1) << 1) | (set ? 1 : 0);
95 } while (Interlocked.CompareExchange (ref state, newValue, oldValue) != oldValue);
99 void CommitChangeToHandle (long stamp)
101 Interlocked.Increment (ref used);
102 var tmpHandle = handle;
103 if (tmpHandle != null) {
104 // First in all case we carry the operation we were called for
105 if ((stamp & 1) == 1)
110 /* Then what may happen is that the two suboperations (state change and handle change)
111 * overlapped with others. In our case it doesn't matter if the two suboperations aren't
112 * executed together at the same time, the only thing we have to make sure of is that both
113 * state and handle are synchronized on the last visible state change.
115 * For instance if S is state change and H is handle change, for 3 concurrent operations
116 * we may have the following serialized timeline: S1 S2 H2 S3 H3 H1
117 * Which is perfectly fine (all S were converted to H at some stage) but in that case
118 * we have a mismatch between S and H at the end because the last operations done were
119 * S3/H1. We thus need to repeat H3 to get to the desired final state.
123 currentState = state;
124 if (currentState != stamp && (stamp & 1) != (currentState & 1)) {
125 if ((currentState & 1) == 1)
130 } while (currentState != state);
132 Interlocked.Decrement (ref used);
137 Wait (CancellationToken.None);
140 public bool Wait (int millisecondsTimeout)
142 return Wait (millisecondsTimeout, CancellationToken.None);
145 public bool Wait (TimeSpan timeout)
147 return Wait (CheckTimeout (timeout), CancellationToken.None);
150 public void Wait (CancellationToken cancellationToken)
152 Wait (Timeout.Infinite, cancellationToken);
155 public bool Wait (int millisecondsTimeout, CancellationToken cancellationToken)
157 if (millisecondsTimeout < -1)
158 throw new ArgumentOutOfRangeException ("millisecondsTimeout");
163 SpinWait wait = new SpinWait ();
166 if (wait.Count < spinCount) {
174 cancellationToken.ThrowIfCancellationRequested ();
179 WaitHandle handle = WaitHandle;
181 if (cancellationToken.CanBeCanceled) {
182 var result = WaitHandle.WaitAny (new[] { handle, cancellationToken.WaitHandle }, millisecondsTimeout, false);
184 throw new OperationCanceledException (cancellationToken);
185 if (result == WaitHandle.WaitTimeout)
188 if (!handle.WaitOne (millisecondsTimeout, false))
196 public bool Wait (TimeSpan timeout, CancellationToken cancellationToken)
198 return Wait (CheckTimeout (timeout), cancellationToken);
201 public WaitHandle WaitHandle {
209 var mre = new ManualResetEvent (IsSet);
210 if (Interlocked.CompareExchange (ref handle, mre, null) == null) {
212 // Ensure the Set has not ran meantime
214 if (isSet != IsSet) {
223 // Release the event when other thread was faster
232 public void Dispose ()
237 protected virtual void Dispose (bool disposing)
239 if (!disposed.TryRelaxedSet ())
242 if (handle != null) {
243 var tmpHandle = Interlocked.Exchange (ref handle, null);
245 // A tiny wait (just a few cycles normally) before releasing
246 SpinWait wait = new SpinWait ();
250 tmpHandle.Dispose ();
254 void ThrowIfDisposed ()
257 throw new ObjectDisposedException ("ManualResetEventSlim");
260 static int CheckTimeout (TimeSpan timeout)
263 return checked ((int)timeout.TotalMilliseconds);
264 } catch (System.OverflowException) {
265 throw new ArgumentOutOfRangeException ("timeout");