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 ()
219 void IDisposable.Dispose ()
225 public const int WaitTimeout = 258;
228 // In 2.0 we use SafeWaitHandles instead of IntPtrs
230 SafeWaitHandle safe_wait_handle;
232 [Obsolete ("In the profiles > 2.x, use SafeHandle instead of Handle")]
233 public virtual IntPtr Handle {
235 return safe_wait_handle.DangerousGetHandle ();
238 [SecurityPermission (SecurityAction.LinkDemand, UnmanagedCode = true)]
239 [SecurityPermission (SecurityAction.InheritanceDemand, UnmanagedCode = true)]
241 if (value == InvalidHandle)
242 safe_wait_handle = new SafeWaitHandle (InvalidHandle, false);
244 safe_wait_handle = new SafeWaitHandle (value, true);
248 [MethodImplAttribute(MethodImplOptions.InternalCall)]
249 private extern bool WaitOne_internal(IntPtr handle, int ms, bool exitContext);
251 protected virtual void Dispose (bool explicitDisposing)
257 // This is only the case if the handle was never properly initialized
258 // most likely a bug in the derived class
260 if (safe_wait_handle == null)
264 if (safe_wait_handle != null)
265 safe_wait_handle.Dispose ();
270 public SafeWaitHandle SafeWaitHandle {
271 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.MayFail)]
273 return safe_wait_handle;
276 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
279 safe_wait_handle = new SafeWaitHandle (InvalidHandle, false);
281 safe_wait_handle = value;
285 public static bool SignalAndWait (WaitHandle toSignal,
288 return SignalAndWait (toSignal, toWaitOn, -1, false);
291 public static bool SignalAndWait (WaitHandle toSignal,
293 int millisecondsTimeout,
296 if (toSignal == null)
297 throw new ArgumentNullException ("toSignal");
298 if (toWaitOn == null)
299 throw new ArgumentNullException ("toWaitOn");
301 if (millisecondsTimeout < -1)
302 throw new ArgumentOutOfRangeException ("millisecondsTimeout");
304 return SignalAndWait_Internal (toSignal.Handle, toWaitOn.Handle, millisecondsTimeout, exitContext);
307 public static bool SignalAndWait (WaitHandle toSignal,
312 double ms = timeout.TotalMilliseconds;
313 if (ms > Int32.MaxValue)
314 throw new ArgumentOutOfRangeException ("timeout");
316 return SignalAndWait (toSignal, toWaitOn, Convert.ToInt32 (ms), false);
319 [MethodImplAttribute(MethodImplOptions.InternalCall)]
320 static extern bool SignalAndWait_Internal (IntPtr toSignal, IntPtr toWaitOn, int ms, bool exitContext);
322 public virtual bool WaitOne()
325 bool release = false;
327 safe_wait_handle.DangerousAddRef (ref release);
328 return (WaitOne_internal(safe_wait_handle.DangerousGetHandle (), Timeout.Infinite, false));
331 safe_wait_handle.DangerousRelease ();
335 public virtual bool WaitOne(int millisecondsTimeout, bool exitContext)
338 // check negative - except for -1 (which is Timeout.Infinite)
339 if (millisecondsTimeout < Timeout.Infinite)
340 throw new ArgumentOutOfRangeException ("millisecondsTimeout");
342 bool release = false;
345 SynchronizationAttribute.ExitContext ();
346 safe_wait_handle.DangerousAddRef (ref release);
347 return (WaitOne_internal(safe_wait_handle.DangerousGetHandle (), millisecondsTimeout, exitContext));
350 SynchronizationAttribute.EnterContext ();
352 safe_wait_handle.DangerousRelease ();
356 public virtual bool WaitOne (int millisecondsTimeout)
358 return WaitOne (millisecondsTimeout, false);
361 public virtual bool WaitOne (TimeSpan timeout)
363 return WaitOne (timeout, false);
366 public virtual bool WaitOne(TimeSpan timeout, bool exitContext)
369 long ms = (long) timeout.TotalMilliseconds;
370 if (ms < -1 || ms > Int32.MaxValue)
371 throw new ArgumentOutOfRangeException ("timeout");
373 bool release = false;
376 SynchronizationAttribute.ExitContext ();
377 safe_wait_handle.DangerousAddRef (ref release);
378 return (WaitOne_internal(safe_wait_handle.DangerousGetHandle (), (int) ms, exitContext));
382 SynchronizationAttribute.EnterContext ();
384 safe_wait_handle.DangerousRelease ();
388 internal void CheckDisposed ()
390 if (disposed || safe_wait_handle == null)
391 throw new ObjectDisposedException (GetType ().FullName);
394 public static bool WaitAll(WaitHandle[] waitHandles, int millisecondsTimeout)
396 return WaitAll (waitHandles, millisecondsTimeout, false);
399 public static bool WaitAll(WaitHandle[] waitHandles, TimeSpan timeout)
401 return WaitAll (waitHandles, timeout, false);
404 protected static readonly IntPtr InvalidHandle = (IntPtr) (-1);
405 bool disposed = false;