Remove now useless barriers in ManualResetEventSlim since Interlocked do the job...
[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                 int 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                                 Interlocked.Increment (ref used);
82                                 var tmpHandle = handle;
83                                 if (tmpHandle != null)
84                                         tmpHandle.Reset ();
85                                 Interlocked.Decrement (ref used);
86                         }
87                 }
88
89                 public void Set ()
90                 {
91                         set = true;
92                         Thread.MemoryBarrier ();
93                         if (handle != null) {
94                                 Interlocked.Increment (ref used);
95                                 var tmpHandle = handle;
96                                 if (tmpHandle != null)
97                                         tmpHandle.Set ();
98                                 Interlocked.Decrement (ref used);
99                         }
100                 }
101
102                 public void Wait ()
103                 {
104                         Wait (CancellationToken.None);
105                 }
106
107                 public bool Wait (int millisecondsTimeout)
108                 {
109                         return Wait (millisecondsTimeout, CancellationToken.None);
110                 }
111
112                 public bool Wait (TimeSpan timeout)
113                 {
114                         return Wait (CheckTimeout (timeout), CancellationToken.None);
115                 }
116
117                 public void Wait (CancellationToken cancellationToken)
118                 {
119                         Wait (Timeout.Infinite, cancellationToken);
120                 }
121
122                 public bool Wait (int millisecondsTimeout, CancellationToken cancellationToken)
123                 {
124                         if (millisecondsTimeout < -1)
125                                 throw new ArgumentOutOfRangeException ("millisecondsTimeout");
126
127                         ThrowIfDisposed ();
128
129                         if (!set) {
130                                 SpinWait wait = new SpinWait ();
131
132                                 while (!set) {
133                                         cancellationToken.ThrowIfCancellationRequested ();
134
135                                         if (wait.Count < spinCount) {
136                                                 wait.SpinOnce ();
137                                                 continue;
138                                         }
139
140                                         break;
141                                 }
142
143                                 if (set)
144                                         return true;
145
146                                 WaitHandle handle = WaitHandle;
147
148                                 if (cancellationToken.CanBeCanceled) {
149                                         if (WaitHandle.WaitAny (new[] { handle, cancellationToken.WaitHandle }, millisecondsTimeout, false) == 0)
150                                                 return false;
151
152                                         cancellationToken.ThrowIfCancellationRequested ();
153                                 } else {
154                                         if (!handle.WaitOne (millisecondsTimeout, false))
155                                                 return false;
156                                 }
157                         }
158
159                         return true;
160                 }
161
162                 public bool Wait (TimeSpan timeout, CancellationToken cancellationToken)
163                 {
164                         return Wait (CheckTimeout (timeout), cancellationToken);
165                 }
166
167                 public WaitHandle WaitHandle {
168                         get {
169                                 ThrowIfDisposed ();
170
171                                 if (handle != null)
172                                         return handle;
173
174                                 var isSet = set;
175                                 var mre = new ManualResetEvent (isSet);
176                                 if (Interlocked.CompareExchange (ref handle, mre, null) == null) {
177                                         //
178                                         // Ensure the Set has not ran meantime
179                                         //
180                                         if (isSet != set) {
181                                                 if (set) {
182                                                         mre.Set ();
183                                                 } else {
184                                                         mre.Reset ();
185                                                 }
186                                         }
187                                 } else {
188                                         //
189                                         // Release the event when other thread was faster
190                                         //
191                                         mre.Dispose ();
192                                 }
193
194                                 return handle;
195                         }
196                 }
197
198                 public void Dispose ()
199                 {
200                         Dispose (true);
201                 }
202
203                 protected virtual void Dispose (bool disposing)
204                 {
205                         if (!disposed.TryRelaxedSet ())
206                                 return;
207
208                         if (handle != null) {
209                                 var tmpHandle = Interlocked.Exchange (ref handle, null);
210                                 if (used > 0) {
211                                         // A tiny wait (just a few cycles normally) before releasing
212                                         SpinWait wait = new SpinWait ();
213                                         while (used > 0)
214                                                 wait.SpinOnce ();
215                                 }
216                                 tmpHandle.Dispose ();
217                         }
218                 }
219
220                 void ThrowIfDisposed ()
221                 {
222                         if (disposed.Value)
223                                 throw new ObjectDisposedException ("ManualResetEventSlim");
224                 }
225
226                 static int CheckTimeout (TimeSpan timeout)
227                 {
228                         try {
229                                 return checked ((int)timeout.TotalMilliseconds);
230                         } catch (System.OverflowException) {
231                                 throw new ArgumentOutOfRangeException ("timeout");
232                         }
233                 }
234         }
235 }
236 #endif