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 [StructLayout (LayoutKind.Sequential)]
44 public abstract class WaitHandle
45 : MarshalByRefObject, IDisposable
47 [MethodImplAttribute(MethodImplOptions.InternalCall)]
48 private static extern bool WaitAll_internal(WaitHandle[] handles, int ms, bool exitContext);
50 static void CheckArray (WaitHandle [] handles, bool waitAll)
53 throw new ArgumentNullException ("waitHandles");
55 int length = handles.Length;
57 throw new NotSupportedException ("Too many handles");
59 if (handles.Length == 0) {
60 // MS throws different exceptions from the different methods.
62 throw new ArgumentNullException ("waitHandles");
64 throw new ArgumentException ();
69 // Although we should thrown an exception if this is an STA thread,
70 // Mono does not know anything about STA threads, and just makes
71 // things like Paint.NET not even possible to work.
73 // See bug #78455 for the bug this is supposed to fix.
75 if (waitAll && length > 1 && IsSTAThread)
76 throw new NotSupportedException ("WaitAll for multiple handles is not allowed on an STA thread.");
78 foreach (WaitHandle w in handles) {
80 throw new ArgumentNullException ("waitHandles", "null handle");
82 if (w.safe_wait_handle == null)
83 throw new ArgumentException ("null element found", "waitHandle");
88 // usage of property is commented - see above
89 static bool IsSTAThread {
91 bool isSTA = Thread.CurrentThread.ApartmentState ==
94 // FIXME: remove this check after Thread.ApartmentState
95 // has been properly implemented.
97 Assembly asm = Assembly.GetEntryAssembly ();
99 isSTA = asm.EntryPoint.GetCustomAttributes (typeof (STAThreadAttribute), false).Length > 0;
106 public static bool WaitAll(WaitHandle[] waitHandles)
108 CheckArray (waitHandles, true);
109 return(WaitAll_internal(waitHandles, Timeout.Infinite, false));
112 public static bool WaitAll(WaitHandle[] waitHandles, int millisecondsTimeout, bool exitContext)
114 CheckArray (waitHandles, true);
115 // check negative - except for -1 (which is Timeout.Infinite)
116 if (millisecondsTimeout < Timeout.Infinite)
117 throw new ArgumentOutOfRangeException ("millisecondsTimeout");
122 throw new NotSupportedException ("exitContext == true is not supported");
124 SynchronizationAttribute.ExitContext ();
127 return(WaitAll_internal(waitHandles, millisecondsTimeout, false));
130 if (exitContext) SynchronizationAttribute.EnterContext ();
134 public static bool WaitAll(WaitHandle[] waitHandles,
138 CheckArray (waitHandles, true);
139 long ms = (long) timeout.TotalMilliseconds;
141 if (ms < -1 || ms > Int32.MaxValue)
142 throw new ArgumentOutOfRangeException ("timeout");
147 throw new NotSupportedException ("exitContext == true is not supported");
149 SynchronizationAttribute.ExitContext ();
152 return (WaitAll_internal (waitHandles, (int) ms, exitContext));
155 if (exitContext) SynchronizationAttribute.EnterContext ();
159 [MethodImplAttribute(MethodImplOptions.InternalCall)]
160 private static extern int WaitAny_internal(WaitHandle[] handles, int ms, bool exitContext);
162 // LAMESPEC: Doesn't specify how to signal failures
163 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.MayFail)]
164 public static int WaitAny(WaitHandle[] waitHandles)
166 CheckArray (waitHandles, false);
167 return(WaitAny_internal(waitHandles, Timeout.Infinite, false));
170 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.MayFail)]
171 public static int WaitAny(WaitHandle[] waitHandles,
172 int millisecondsTimeout,
175 CheckArray (waitHandles, false);
176 // check negative - except for -1 (which is Timeout.Infinite)
177 if (millisecondsTimeout < Timeout.Infinite)
178 throw new ArgumentOutOfRangeException ("millisecondsTimeout");
183 throw new NotSupportedException ("exitContext == true is not supported");
185 SynchronizationAttribute.ExitContext ();
188 return(WaitAny_internal(waitHandles, millisecondsTimeout, exitContext));
191 if (exitContext) SynchronizationAttribute.EnterContext ();
195 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.MayFail)]
196 public static int WaitAny(WaitHandle[] waitHandles, TimeSpan timeout)
198 return WaitAny (waitHandles, timeout, false);
201 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.MayFail)]
202 public static int WaitAny(WaitHandle[] waitHandles, int millisecondsTimeout)
204 return WaitAny (waitHandles, millisecondsTimeout, false);
207 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.MayFail)]
208 public static int WaitAny(WaitHandle[] waitHandles,
209 TimeSpan timeout, bool exitContext)
211 CheckArray (waitHandles, false);
212 long ms = (long) timeout.TotalMilliseconds;
214 if (ms < -1 || ms > Int32.MaxValue)
215 throw new ArgumentOutOfRangeException ("timeout");
220 throw new NotSupportedException ("exitContext == true is not supported");
222 SynchronizationAttribute.ExitContext ();
225 return (WaitAny_internal(waitHandles, (int) ms, exitContext));
228 if (exitContext) SynchronizationAttribute.EnterContext ();
232 protected WaitHandle()
237 public virtual void Close ()
242 public void Dispose ()
247 public const int WaitTimeout = 258;
250 // In 2.0 we use SafeWaitHandles instead of IntPtrs
252 SafeWaitHandle safe_wait_handle;
254 [Obsolete ("In the profiles > 2.x, use SafeHandle instead of Handle")]
255 public virtual IntPtr Handle {
257 return safe_wait_handle.DangerousGetHandle ();
260 [SecurityPermission (SecurityAction.LinkDemand, UnmanagedCode = true)]
261 [SecurityPermission (SecurityAction.InheritanceDemand, UnmanagedCode = true)]
263 if (value == InvalidHandle)
264 safe_wait_handle = new SafeWaitHandle (InvalidHandle, false);
266 safe_wait_handle = new SafeWaitHandle (value, true);
270 [MethodImplAttribute(MethodImplOptions.InternalCall)]
271 private extern bool WaitOne_internal(IntPtr handle, int ms, bool exitContext);
273 protected virtual void Dispose (bool explicitDisposing)
278 // This is only the case if the handle was never properly initialized
279 // most likely a bug in the derived class
281 if (safe_wait_handle == null)
289 if (safe_wait_handle != null)
290 safe_wait_handle.Dispose ();
295 public SafeWaitHandle SafeWaitHandle {
296 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.MayFail)]
298 return safe_wait_handle;
301 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
304 safe_wait_handle = new SafeWaitHandle (InvalidHandle, false);
306 safe_wait_handle = value;
310 public static bool SignalAndWait (WaitHandle toSignal,
313 return SignalAndWait (toSignal, toWaitOn, -1, false);
316 public static bool SignalAndWait (WaitHandle toSignal,
318 int millisecondsTimeout,
321 if (toSignal == null)
322 throw new ArgumentNullException ("toSignal");
323 if (toWaitOn == null)
324 throw new ArgumentNullException ("toWaitOn");
326 if (millisecondsTimeout < -1)
327 throw new ArgumentOutOfRangeException ("millisecondsTimeout");
329 return SignalAndWait_Internal (toSignal.Handle, toWaitOn.Handle, millisecondsTimeout, exitContext);
332 public static bool SignalAndWait (WaitHandle toSignal,
337 double ms = timeout.TotalMilliseconds;
338 if (ms > Int32.MaxValue)
339 throw new ArgumentOutOfRangeException ("timeout");
341 return SignalAndWait (toSignal, toWaitOn, Convert.ToInt32 (ms), false);
344 [MethodImplAttribute(MethodImplOptions.InternalCall)]
345 static extern bool SignalAndWait_Internal (IntPtr toSignal, IntPtr toWaitOn, int ms, bool exitContext);
347 public virtual bool WaitOne()
350 bool release = false;
352 safe_wait_handle.DangerousAddRef (ref release);
353 return (WaitOne_internal(safe_wait_handle.DangerousGetHandle (), Timeout.Infinite, false));
356 safe_wait_handle.DangerousRelease ();
360 public virtual bool WaitOne(int millisecondsTimeout, bool exitContext)
363 // check negative - except for -1 (which is Timeout.Infinite)
364 if (millisecondsTimeout < Timeout.Infinite)
365 throw new ArgumentOutOfRangeException ("millisecondsTimeout");
367 bool release = false;
371 SynchronizationAttribute.ExitContext ();
374 safe_wait_handle.DangerousAddRef (ref release);
375 return (WaitOne_internal(safe_wait_handle.DangerousGetHandle (), millisecondsTimeout, exitContext));
379 SynchronizationAttribute.EnterContext ();
382 safe_wait_handle.DangerousRelease ();
386 public virtual bool WaitOne (int millisecondsTimeout)
388 return WaitOne (millisecondsTimeout, false);
391 public virtual bool WaitOne (TimeSpan timeout)
393 return WaitOne (timeout, false);
396 public virtual bool WaitOne(TimeSpan timeout, bool exitContext)
399 long ms = (long) timeout.TotalMilliseconds;
400 if (ms < -1 || ms > Int32.MaxValue)
401 throw new ArgumentOutOfRangeException ("timeout");
403 bool release = false;
407 SynchronizationAttribute.ExitContext ();
410 safe_wait_handle.DangerousAddRef (ref release);
411 return (WaitOne_internal(safe_wait_handle.DangerousGetHandle (), (int) ms, exitContext));
416 SynchronizationAttribute.EnterContext ();
419 safe_wait_handle.DangerousRelease ();
423 internal void CheckDisposed ()
425 if (disposed || safe_wait_handle == null)
426 throw new ObjectDisposedException (GetType ().FullName);
429 public static bool WaitAll(WaitHandle[] waitHandles, int millisecondsTimeout)
431 return WaitAll (waitHandles, millisecondsTimeout, false);
434 public static bool WaitAll(WaitHandle[] waitHandles, TimeSpan timeout)
436 return WaitAll (waitHandles, timeout, false);
439 protected static readonly IntPtr InvalidHandle = (IntPtr) (-1);
440 bool disposed = false;