2 // System.Threading.WaitHandle.cs
5 // Dick Porter (dick@ximian.com)
6 // Gonzalo Paniagua Javier (gonzalo@ximian.com
8 // (C) 2002,2003 Ximian, Inc. (http://www.ximian.com)
9 // Copyright (C) 2004-2005 Novell, Inc (http://www.novell.com)
11 // Permission is hereby granted, free of charge, to any person obtaining
12 // a copy of this software and associated documentation files (the
13 // "Software"), to deal in the Software without restriction, including
14 // without limitation the rights to use, copy, modify, merge, publish,
15 // distribute, sublicense, and/or sell copies of the Software, and to
16 // permit persons to whom the Software is furnished to do so, subject to
17 // the following conditions:
19 // The above copyright notice and this permission notice shall be
20 // included in all copies or substantial portions of the Software.
22 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
23 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
24 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
25 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
26 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
27 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
28 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
32 using System.Reflection;
33 using System.Runtime.CompilerServices;
34 using System.Runtime.Remoting.Contexts;
35 using System.Security.Permissions;
36 using System.Runtime.InteropServices;
37 using Microsoft.Win32.SafeHandles;
38 using System.Runtime.ConstrainedExecution;
40 namespace System.Threading
43 public abstract class WaitHandle : MarshalByRefObject, IDisposable
45 [MethodImplAttribute(MethodImplOptions.InternalCall)]
46 private static extern bool WaitAll_internal(WaitHandle[] handles, int ms, bool exitContext);
48 static void CheckArray (WaitHandle [] handles, bool waitAll)
51 throw new ArgumentNullException ("waitHandles");
53 int length = handles.Length;
55 throw new NotSupportedException ("Too many handles");
57 if (handles.Length == 0) {
58 // MS throws different exceptions from the different methods.
60 throw new ArgumentNullException ("waitHandles");
62 throw new ArgumentException ();
67 // Although we should thrown an exception if this is an STA thread,
68 // Mono does not know anything about STA threads, and just makes
69 // things like Paint.NET not even possible to work.
71 // See bug #78455 for the bug this is supposed to fix.
73 if (waitAll && length > 1 && IsSTAThread)
74 throw new NotSupportedException ("WaitAll for multiple handles is not allowed on an STA thread.");
76 foreach (WaitHandle w in handles) {
78 throw new ArgumentNullException ("waitHandles", "null handle");
80 if (w.safe_wait_handle == null)
81 throw new ArgumentException ("null element found", "waitHandle");
86 // usage of property is commented - see above
87 static bool IsSTAThread {
89 bool isSTA = Thread.CurrentThread.ApartmentState ==
92 // FIXME: remove this check after Thread.ApartmentState
93 // has been properly implemented.
95 Assembly asm = Assembly.GetEntryAssembly ();
97 isSTA = asm.EntryPoint.GetCustomAttributes (typeof (STAThreadAttribute), false).Length > 0;
104 public static bool WaitAll(WaitHandle[] waitHandles)
106 CheckArray (waitHandles, true);
107 return(WaitAll_internal(waitHandles, Timeout.Infinite, false));
110 public static bool WaitAll(WaitHandle[] waitHandles, int millisecondsTimeout, bool exitContext)
112 CheckArray (waitHandles, true);
113 // check negative - except for -1 (which is Timeout.Infinite)
114 if (millisecondsTimeout < Timeout.Infinite)
115 throw new ArgumentOutOfRangeException ("millisecondsTimeout");
118 if (exitContext) SynchronizationAttribute.ExitContext ();
119 return(WaitAll_internal(waitHandles, millisecondsTimeout, false));
122 if (exitContext) SynchronizationAttribute.EnterContext ();
126 public static bool WaitAll(WaitHandle[] waitHandles,
130 CheckArray (waitHandles, true);
131 long ms = (long) timeout.TotalMilliseconds;
133 if (ms < -1 || ms > Int32.MaxValue)
134 throw new ArgumentOutOfRangeException ("timeout");
137 if (exitContext) SynchronizationAttribute.ExitContext ();
138 return (WaitAll_internal (waitHandles, (int) ms, exitContext));
141 if (exitContext) SynchronizationAttribute.EnterContext ();
145 [MethodImplAttribute(MethodImplOptions.InternalCall)]
146 private static extern int WaitAny_internal(WaitHandle[] handles, int ms, bool exitContext);
148 // LAMESPEC: Doesn't specify how to signal failures
149 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.MayFail)]
150 public static int WaitAny(WaitHandle[] waitHandles)
152 CheckArray (waitHandles, false);
153 return(WaitAny_internal(waitHandles, Timeout.Infinite, false));
156 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.MayFail)]
157 public static int WaitAny(WaitHandle[] waitHandles,
158 int millisecondsTimeout,
161 CheckArray (waitHandles, false);
162 // check negative - except for -1 (which is Timeout.Infinite)
163 if (millisecondsTimeout < Timeout.Infinite)
164 throw new ArgumentOutOfRangeException ("millisecondsTimeout");
167 if (exitContext) SynchronizationAttribute.ExitContext ();
168 return(WaitAny_internal(waitHandles, millisecondsTimeout, exitContext));
171 if (exitContext) SynchronizationAttribute.EnterContext ();
175 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.MayFail)]
176 public static int WaitAny(WaitHandle[] waitHandles, TimeSpan timeout)
178 return WaitAny (waitHandles, timeout, false);
181 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.MayFail)]
182 public static int WaitAny(WaitHandle[] waitHandles, int millisecondsTimeout)
184 return WaitAny (waitHandles, millisecondsTimeout, false);
187 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.MayFail)]
188 public static int WaitAny(WaitHandle[] waitHandles,
189 TimeSpan timeout, bool exitContext)
191 CheckArray (waitHandles, false);
192 long ms = (long) timeout.TotalMilliseconds;
194 if (ms < -1 || ms > Int32.MaxValue)
195 throw new ArgumentOutOfRangeException ("timeout");
198 if (exitContext) SynchronizationAttribute.ExitContext ();
199 return (WaitAny_internal(waitHandles, (int) ms, exitContext));
202 if (exitContext) SynchronizationAttribute.EnterContext ();
206 protected WaitHandle()
211 public virtual void Close() {
213 GC.SuppressFinalize (this);
217 public void Dispose ()
223 public const int WaitTimeout = 258;
226 // In 2.0 we use SafeWaitHandles instead of IntPtrs
228 SafeWaitHandle safe_wait_handle;
230 [Obsolete ("In the profiles > 2.x, use SafeHandle instead of Handle")]
231 public virtual IntPtr Handle {
233 return safe_wait_handle.DangerousGetHandle ();
236 [SecurityPermission (SecurityAction.LinkDemand, UnmanagedCode = true)]
237 [SecurityPermission (SecurityAction.InheritanceDemand, UnmanagedCode = true)]
239 if (value == InvalidHandle)
240 safe_wait_handle = new SafeWaitHandle (InvalidHandle, false);
242 safe_wait_handle = new SafeWaitHandle (value, true);
246 [MethodImplAttribute(MethodImplOptions.InternalCall)]
247 private extern bool WaitOne_internal(IntPtr handle, int ms, bool exitContext);
249 protected virtual void Dispose (bool explicitDisposing)
255 // This is only the case if the handle was never properly initialized
256 // most likely a bug in the derived class
258 if (safe_wait_handle == null)
262 if (safe_wait_handle != null)
263 safe_wait_handle.Dispose ();
268 public SafeWaitHandle SafeWaitHandle {
269 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.MayFail)]
271 return safe_wait_handle;
274 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
277 safe_wait_handle = new SafeWaitHandle (InvalidHandle, false);
279 safe_wait_handle = value;
283 public static bool SignalAndWait (WaitHandle toSignal,
286 return SignalAndWait (toSignal, toWaitOn, -1, false);
289 public static bool SignalAndWait (WaitHandle toSignal,
291 int millisecondsTimeout,
294 if (toSignal == null)
295 throw new ArgumentNullException ("toSignal");
296 if (toWaitOn == null)
297 throw new ArgumentNullException ("toWaitOn");
299 if (millisecondsTimeout < -1)
300 throw new ArgumentOutOfRangeException ("millisecondsTimeout");
302 return SignalAndWait_Internal (toSignal.Handle, toWaitOn.Handle, millisecondsTimeout, exitContext);
305 public static bool SignalAndWait (WaitHandle toSignal,
310 double ms = timeout.TotalMilliseconds;
311 if (ms > Int32.MaxValue)
312 throw new ArgumentOutOfRangeException ("timeout");
314 return SignalAndWait (toSignal, toWaitOn, Convert.ToInt32 (ms), false);
317 [MethodImplAttribute(MethodImplOptions.InternalCall)]
318 static extern bool SignalAndWait_Internal (IntPtr toSignal, IntPtr toWaitOn, int ms, bool exitContext);
320 public virtual bool WaitOne()
323 bool release = false;
325 safe_wait_handle.DangerousAddRef (ref release);
326 return (WaitOne_internal(safe_wait_handle.DangerousGetHandle (), Timeout.Infinite, false));
329 safe_wait_handle.DangerousRelease ();
333 public virtual bool WaitOne(int millisecondsTimeout, bool exitContext)
336 // check negative - except for -1 (which is Timeout.Infinite)
337 if (millisecondsTimeout < Timeout.Infinite)
338 throw new ArgumentOutOfRangeException ("millisecondsTimeout");
340 bool release = false;
343 SynchronizationAttribute.ExitContext ();
344 safe_wait_handle.DangerousAddRef (ref release);
345 return (WaitOne_internal(safe_wait_handle.DangerousGetHandle (), millisecondsTimeout, exitContext));
348 SynchronizationAttribute.EnterContext ();
350 safe_wait_handle.DangerousRelease ();
354 public virtual bool WaitOne (int millisecondsTimeout)
356 return WaitOne (millisecondsTimeout, false);
359 public virtual bool WaitOne (TimeSpan timeout)
361 return WaitOne (timeout, false);
364 public virtual bool WaitOne(TimeSpan timeout, bool exitContext)
367 long ms = (long) timeout.TotalMilliseconds;
368 if (ms < -1 || ms > Int32.MaxValue)
369 throw new ArgumentOutOfRangeException ("timeout");
371 bool release = false;
374 SynchronizationAttribute.ExitContext ();
375 safe_wait_handle.DangerousAddRef (ref release);
376 return (WaitOne_internal(safe_wait_handle.DangerousGetHandle (), (int) ms, exitContext));
380 SynchronizationAttribute.EnterContext ();
382 safe_wait_handle.DangerousRelease ();
386 internal void CheckDisposed ()
388 if (disposed || safe_wait_handle == null)
389 throw new ObjectDisposedException (GetType ().FullName);
392 public static bool WaitAll(WaitHandle[] waitHandles, int millisecondsTimeout)
394 return WaitAll (waitHandles, millisecondsTimeout, false);
397 public static bool WaitAll(WaitHandle[] waitHandles, TimeSpan timeout)
399 return WaitAll (waitHandles, timeout, false);
402 protected static readonly IntPtr InvalidHandle = (IntPtr) (-1);
403 bool disposed = false;
405 void IDisposable.Dispose() {
407 // Take yourself off the Finalization queue
408 GC.SuppressFinalize(this);