Merge pull request #217 from QuickJack/master
[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 #if NET_4_0 || MOBILE
30
31 namespace System.Threading
32 {
33         [System.Diagnostics.DebuggerDisplayAttribute ("Set = {IsSet}")]
34         public class ManualResetEventSlim : IDisposable
35         {
36                 readonly int spinCount;
37
38                 ManualResetEvent handle;
39                 internal AtomicBooleanValue disposed;
40                 bool used;
41                 bool set;
42
43                 public ManualResetEventSlim ()
44                         : this (false, 10)
45                 {
46                 }
47
48                 public ManualResetEventSlim (bool initialState)
49                         : this (initialState, 10)
50                 {
51                 }
52
53                 public ManualResetEventSlim (bool initialState, int spinCount)
54                 {
55                         if (spinCount < 0 || spinCount > 2047)
56                                 throw new ArgumentOutOfRangeException ("spinCount");
57
58                         this.set = initialState;
59                         this.spinCount = spinCount;
60                 }
61
62                 public bool IsSet {
63                         get {
64                                 return set;
65                         }
66                 }
67
68                 public int SpinCount {
69                         get {
70                                 return spinCount;
71                         }
72                 }
73
74                 public void Reset ()
75                 {
76                         ThrowIfDisposed ();
77
78                         set = false;
79                         Thread.MemoryBarrier ();
80                         if (handle != null) {
81                                 used = true;
82                                 Thread.MemoryBarrier ();
83                                 var tmpHandle = handle;
84                                 if (tmpHandle != null)
85                                         tmpHandle.Reset ();
86                                 Thread.MemoryBarrier ();
87                                 used = false;
88                         }
89                 }
90
91                 public void Set ()
92                 {
93                         set = true;
94                         Thread.MemoryBarrier ();
95                         if (handle != null) {
96                                 used = true;
97                                 Thread.MemoryBarrier ();
98                                 var tmpHandle = handle;
99                                 if (tmpHandle != null)
100                                         tmpHandle.Set ();
101                                 Thread.MemoryBarrier ();
102                                 used = false;
103                         }
104                 }
105
106                 public void Wait ()
107                 {
108                         Wait (CancellationToken.None);
109                 }
110
111                 public bool Wait (int millisecondsTimeout)
112                 {
113                         return Wait (millisecondsTimeout, CancellationToken.None);
114                 }
115
116                 public bool Wait (TimeSpan timeout)
117                 {
118                         return Wait (CheckTimeout (timeout), CancellationToken.None);
119                 }
120
121                 public void Wait (CancellationToken cancellationToken)
122                 {
123                         Wait (Timeout.Infinite, cancellationToken);
124                 }
125
126                 public bool Wait (int millisecondsTimeout, CancellationToken cancellationToken)
127                 {
128                         if (millisecondsTimeout < -1)
129                                 throw new ArgumentOutOfRangeException ("millisecondsTimeout");
130
131                         ThrowIfDisposed ();
132
133                         if (!set) {
134                                 SpinWait wait = new SpinWait ();
135
136                                 while (!set) {
137                                         cancellationToken.ThrowIfCancellationRequested ();
138
139                                         if (wait.Count < spinCount) {
140                                                 wait.SpinOnce ();
141                                                 continue;
142                                         }
143
144                                         break;
145                                 }
146
147                                 if (set)
148                                         return true;
149
150                                 WaitHandle handle = WaitHandle;
151
152                                 if (cancellationToken.CanBeCanceled) {
153                                         if (WaitHandle.WaitAny (new[] { handle, cancellationToken.WaitHandle }, millisecondsTimeout, false) == 0)
154                                                 return false;
155
156                                         cancellationToken.ThrowIfCancellationRequested ();
157                                 } else {
158                                         if (!handle.WaitOne (millisecondsTimeout, false))
159                                                 return false;
160                                 }
161                         }
162
163                         return true;
164                 }
165
166                 public bool Wait (TimeSpan timeout, CancellationToken cancellationToken)
167                 {
168                         return Wait (CheckTimeout (timeout), cancellationToken);
169                 }
170
171                 public WaitHandle WaitHandle {
172                         get {
173                                 ThrowIfDisposed ();
174
175                                 if (handle != null)
176                                         return handle;
177
178                                 var isSet = set;
179                                 var mre = new ManualResetEvent (isSet);
180                                 if (Interlocked.CompareExchange (ref handle, mre, null) == null) {
181                                         //
182                                         // Ensure the Set has not ran meantime
183                                         //
184                                         if (isSet != set) {
185                                                 if (set) {
186                                                         mre.Set ();
187                                                 } else {
188                                                         mre.Reset ();
189                                                 }
190                                         }
191                                 } else {
192                                         //
193                                         // Release the event when other thread was faster
194                                         //
195                                         mre.Dispose ();
196                                 }
197
198                                 return handle;
199                         }
200                 }
201
202                 public void Dispose ()
203                 {
204                         Dispose (true);
205                 }
206
207                 protected virtual void Dispose (bool disposing)
208                 {
209                         if (!disposed.TryRelaxedSet ())
210                                 return;
211
212                         if (handle != null) {
213                                 var tmpHandle = Interlocked.Exchange (ref handle, null);
214                                 if (used) {
215                                         // A tiny wait (just a few cycles normally) before releasing
216                                         SpinWait wait = new SpinWait ();
217                                         while (used)
218                                                 wait.SpinOnce ();
219                                 }
220                                 tmpHandle.Dispose ();
221                         }
222                 }
223
224                 void ThrowIfDisposed ()
225                 {
226                         if (disposed.Value)
227                                 throw new ObjectDisposedException ("ManualResetEventSlim");
228                 }
229
230                 static int CheckTimeout (TimeSpan timeout)
231                 {
232                         try {
233                                 return checked ((int)timeout.TotalMilliseconds);
234                         } catch (System.OverflowException) {
235                                 throw new ArgumentOutOfRangeException ("timeout");
236                         }
237                 }
238         }
239 }
240 #endif