[bcl] Remove NET_4_0 defines from class libs.
[mono.git] / mcs / class / corlib / System.Threading / ManualResetEventSlim.cs
1 // ManualResetEventSlim.cs
2 //
3 // Authors:
4 //    Marek Safar  <marek.safar@gmail.com>
5 //
6 // Copyright (c) 2008 Jérémie "Garuma" Laval
7 // Copyright 2011 Xamarin Inc (http://www.xamarin.com).
8 //
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:
15 //
16 // The above copyright notice and this permission notice shall be included in
17 // all copies or substantial portions of the Software.
18 //
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
25 // THE SOFTWARE.
26 //
27 //
28
29
30 namespace System.Threading
31 {
32         [System.Diagnostics.DebuggerDisplayAttribute ("Set = {IsSet}")]
33         public class ManualResetEventSlim : IDisposable
34         {
35                 readonly int spinCount;
36
37                 ManualResetEvent handle;
38                 internal AtomicBooleanValue disposed;
39                 int used;
40                 int state;
41
42                 public ManualResetEventSlim ()
43                         : this (false, 10)
44                 {
45                 }
46
47                 public ManualResetEventSlim (bool initialState)
48                         : this (initialState, 10)
49                 {
50                 }
51
52                 public ManualResetEventSlim (bool initialState, int spinCount)
53                 {
54                         if (spinCount < 0 || spinCount > 2047)
55                                 throw new ArgumentOutOfRangeException ("spinCount");
56
57                         this.state = initialState ? 1 : 0;
58                         this.spinCount = spinCount;
59                 }
60
61                 public bool IsSet {
62                         get {
63                                 return (state & 1) == 1;
64                         }
65                 }
66
67                 public int SpinCount {
68                         get {
69                                 return spinCount;
70                         }
71                 }
72
73                 public void Reset ()
74                 {
75                         ThrowIfDisposed ();
76
77                         var stamp = UpdateStateWithOp (false);
78                         if (handle != null)
79                                 CommitChangeToHandle (stamp);
80                 }
81
82                 public void Set ()
83                 {
84                         var stamp = UpdateStateWithOp (true);
85                         if (handle != null)
86                                 CommitChangeToHandle (stamp);
87                 }
88
89                 long UpdateStateWithOp (bool set)
90                 {
91                         int oldValue, newValue;
92                         do {
93                                 oldValue = state;
94                                 newValue = (int)(((oldValue >> 1) + 1) << 1) | (set ? 1 : 0);
95                         } while (Interlocked.CompareExchange (ref state, newValue, oldValue) != oldValue);
96                         return newValue;
97                 }
98
99                 void CommitChangeToHandle (long stamp)
100                 {
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)
106                                         tmpHandle.Set ();
107                                 else
108                                         tmpHandle.Reset ();
109
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.
114                                  *
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.
120                                  */
121                                 int currentState;
122                                 do {
123                                         currentState = state;
124                                         if (currentState != stamp && (stamp & 1) != (currentState & 1)) {
125                                                 if ((currentState & 1) == 1)
126                                                         tmpHandle.Set ();
127                                                 else
128                                                         tmpHandle.Reset ();
129                                         }
130                                 } while (currentState != state);
131                         }
132                         Interlocked.Decrement (ref used);
133                 }
134
135                 public void Wait ()
136                 {
137                         Wait (CancellationToken.None);
138                 }
139
140                 public bool Wait (int millisecondsTimeout)
141                 {
142                         return Wait (millisecondsTimeout, CancellationToken.None);
143                 }
144
145                 public bool Wait (TimeSpan timeout)
146                 {
147                         return Wait (CheckTimeout (timeout), CancellationToken.None);
148                 }
149
150                 public void Wait (CancellationToken cancellationToken)
151                 {
152                         Wait (Timeout.Infinite, cancellationToken);
153                 }
154
155                 public bool Wait (int millisecondsTimeout, CancellationToken cancellationToken)
156                 {
157                         if (millisecondsTimeout < -1)
158                                 throw new ArgumentOutOfRangeException ("millisecondsTimeout");
159
160                         ThrowIfDisposed ();
161
162                         if (!IsSet) {
163                                 SpinWait wait = new SpinWait ();
164
165                                 while (!IsSet) {
166                                         if (wait.Count < spinCount) {
167                                                 wait.SpinOnce ();
168                                                 continue;
169                                         }
170
171                                         break;
172                                 }
173
174                                 cancellationToken.ThrowIfCancellationRequested ();
175
176                                 if (IsSet)
177                                         return true;
178
179                                 WaitHandle handle = WaitHandle;
180
181                                 if (cancellationToken.CanBeCanceled) {
182                                         var result = WaitHandle.WaitAny (new[] { handle, cancellationToken.WaitHandle }, millisecondsTimeout, false);
183                                         if (result == 1)
184                                                 throw new OperationCanceledException (cancellationToken);
185                                         if (result == WaitHandle.WaitTimeout)
186                                                 return false;
187                                 } else {
188                                         if (!handle.WaitOne (millisecondsTimeout, false))
189                                                 return false;
190                                 }
191                         }
192
193                         return true;
194                 }
195
196                 public bool Wait (TimeSpan timeout, CancellationToken cancellationToken)
197                 {
198                         return Wait (CheckTimeout (timeout), cancellationToken);
199                 }
200
201                 public WaitHandle WaitHandle {
202                         get {
203                                 ThrowIfDisposed ();
204
205                                 if (handle != null)
206                                         return handle;
207
208                                 var isSet = IsSet;
209                                 var mre = new ManualResetEvent (IsSet);
210                                 if (Interlocked.CompareExchange (ref handle, mre, null) == null) {
211                                         //
212                                         // Ensure the Set has not ran meantime
213                                         //
214                                         if (isSet != IsSet) {
215                                                 if (IsSet) {
216                                                         mre.Set ();
217                                                 } else {
218                                                         mre.Reset ();
219                                                 }
220                                         }
221                                 } else {
222                                         //
223                                         // Release the event when other thread was faster
224                                         //
225                                         mre.Dispose ();
226                                 }
227
228                                 return handle;
229                         }
230                 }
231
232                 public void Dispose ()
233                 {
234                         Dispose (true);
235                 }
236
237                 protected virtual void Dispose (bool disposing)
238                 {
239                         if (!disposed.TryRelaxedSet ())
240                                 return;
241
242                         if (handle != null) {
243                                 var tmpHandle = Interlocked.Exchange (ref handle, null);
244                                 if (used > 0) {
245                                         // A tiny wait (just a few cycles normally) before releasing
246                                         SpinWait wait = new SpinWait ();
247                                         while (used > 0)
248                                                 wait.SpinOnce ();
249                                 }
250                                 tmpHandle.Dispose ();
251                         }
252                 }
253
254                 void ThrowIfDisposed ()
255                 {
256                         if (disposed.Value)
257                                 throw new ObjectDisposedException ("ManualResetEventSlim");
258                 }
259
260                 static int CheckTimeout (TimeSpan timeout)
261                 {
262                         try {
263                                 return checked ((int)timeout.TotalMilliseconds);
264                         } catch (System.OverflowException) {
265                                 throw new ArgumentOutOfRangeException ("timeout");
266                         }
267                 }
268         }
269 }