WaitHandle.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  1. //
  2. // System.Threading.WaitHandle.cs
  3. //
  4. // Author:
  5. // Dick Porter ([email protected])
  6. // Gonzalo Paniagua Javier ([email protected]
  7. //
  8. // (C) 2002,2003 Ximian, Inc. (http://www.ximian.com)
  9. // Copyright (C) 2004-2005 Novell, Inc (http://www.novell.com)
  10. //
  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:
  18. //
  19. // The above copyright notice and this permission notice shall be
  20. // included in all copies or substantial portions of the Software.
  21. //
  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.
  29. //
  30. using System;
  31. using System.Reflection;
  32. using System.Runtime.CompilerServices;
  33. using System.Runtime.Remoting.Contexts;
  34. using System.Security.Permissions;
  35. using System.Runtime.InteropServices;
  36. using Microsoft.Win32.SafeHandles;
  37. using System.Runtime.ConstrainedExecution;
  38. namespace System.Threading
  39. {
  40. [ComVisible (true)]
  41. public abstract class WaitHandle : MarshalByRefObject, IDisposable
  42. {
  43. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  44. private static extern bool WaitAll_internal(WaitHandle[] handles, int ms, bool exitContext);
  45. static void CheckArray (WaitHandle [] handles, bool waitAll)
  46. {
  47. if (handles == null)
  48. throw new ArgumentNullException ("waitHandles");
  49. int length = handles.Length;
  50. if (length > 64)
  51. throw new NotSupportedException ("Too many handles");
  52. if (handles.Length == 0) {
  53. // MS throws different exceptions from the different methods.
  54. if (waitAll)
  55. throw new ArgumentNullException ("waitHandles");
  56. else
  57. throw new ArgumentException ();
  58. }
  59. #if false
  60. //
  61. // Although we should thrown an exception if this is an STA thread,
  62. // Mono does not know anything about STA threads, and just makes
  63. // things like Paint.NET not even possible to work.
  64. //
  65. // See bug #78455 for the bug this is supposed to fix.
  66. //
  67. if (waitAll && length > 1 && IsSTAThread)
  68. throw new NotSupportedException ("WaitAll for multiple handles is not allowed on an STA thread.");
  69. #endif
  70. foreach (WaitHandle w in handles) {
  71. if (w == null)
  72. throw new ArgumentNullException ("waitHandles", "null handle");
  73. if (w.safe_wait_handle == null)
  74. throw new ArgumentException ("null element found", "waitHandle");
  75. }
  76. }
  77. #if false
  78. // usage of property is commented - see above
  79. static bool IsSTAThread {
  80. get {
  81. bool isSTA = Thread.CurrentThread.ApartmentState ==
  82. ApartmentState.STA;
  83. // FIXME: remove this check after Thread.ApartmentState
  84. // has been properly implemented.
  85. if (!isSTA) {
  86. Assembly asm = Assembly.GetEntryAssembly ();
  87. if (asm != null)
  88. isSTA = asm.EntryPoint.GetCustomAttributes (typeof (STAThreadAttribute), false).Length > 0;
  89. }
  90. return isSTA;
  91. }
  92. }
  93. #endif
  94. public static bool WaitAll(WaitHandle[] waitHandles)
  95. {
  96. CheckArray (waitHandles, true);
  97. return(WaitAll_internal(waitHandles, Timeout.Infinite, false));
  98. }
  99. public static bool WaitAll(WaitHandle[] waitHandles, int millisecondsTimeout, bool exitContext)
  100. {
  101. CheckArray (waitHandles, true);
  102. // check negative - except for -1 (which is Timeout.Infinite)
  103. if (millisecondsTimeout < Timeout.Infinite)
  104. throw new ArgumentOutOfRangeException ("millisecondsTimeout");
  105. try {
  106. if (exitContext) SynchronizationAttribute.ExitContext ();
  107. return(WaitAll_internal(waitHandles, millisecondsTimeout, false));
  108. }
  109. finally {
  110. if (exitContext) SynchronizationAttribute.EnterContext ();
  111. }
  112. }
  113. public static bool WaitAll(WaitHandle[] waitHandles,
  114. TimeSpan timeout,
  115. bool exitContext)
  116. {
  117. CheckArray (waitHandles, true);
  118. long ms = (long) timeout.TotalMilliseconds;
  119. if (ms < -1 || ms > Int32.MaxValue)
  120. throw new ArgumentOutOfRangeException ("timeout");
  121. try {
  122. if (exitContext) SynchronizationAttribute.ExitContext ();
  123. return (WaitAll_internal (waitHandles, (int) ms, exitContext));
  124. }
  125. finally {
  126. if (exitContext) SynchronizationAttribute.EnterContext ();
  127. }
  128. }
  129. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  130. private static extern int WaitAny_internal(WaitHandle[] handles, int ms, bool exitContext);
  131. // LAMESPEC: Doesn't specify how to signal failures
  132. [ReliabilityContract (Consistency.WillNotCorruptState, Cer.MayFail)]
  133. public static int WaitAny(WaitHandle[] waitHandles)
  134. {
  135. CheckArray (waitHandles, false);
  136. return(WaitAny_internal(waitHandles, Timeout.Infinite, false));
  137. }
  138. [ReliabilityContract (Consistency.WillNotCorruptState, Cer.MayFail)]
  139. public static int WaitAny(WaitHandle[] waitHandles,
  140. int millisecondsTimeout,
  141. bool exitContext)
  142. {
  143. CheckArray (waitHandles, false);
  144. // check negative - except for -1 (which is Timeout.Infinite)
  145. if (millisecondsTimeout < Timeout.Infinite)
  146. throw new ArgumentOutOfRangeException ("millisecondsTimeout");
  147. try {
  148. if (exitContext) SynchronizationAttribute.ExitContext ();
  149. return(WaitAny_internal(waitHandles, millisecondsTimeout, exitContext));
  150. }
  151. finally {
  152. if (exitContext) SynchronizationAttribute.EnterContext ();
  153. }
  154. }
  155. [ReliabilityContract (Consistency.WillNotCorruptState, Cer.MayFail)]
  156. public static int WaitAny(WaitHandle[] waitHandles, TimeSpan timeout)
  157. {
  158. return WaitAny (waitHandles, timeout, false);
  159. }
  160. [ReliabilityContract (Consistency.WillNotCorruptState, Cer.MayFail)]
  161. public static int WaitAny(WaitHandle[] waitHandles, int millisecondsTimeout)
  162. {
  163. return WaitAny (waitHandles, millisecondsTimeout, false);
  164. }
  165. [ReliabilityContract (Consistency.WillNotCorruptState, Cer.MayFail)]
  166. public static int WaitAny(WaitHandle[] waitHandles,
  167. TimeSpan timeout, bool exitContext)
  168. {
  169. CheckArray (waitHandles, false);
  170. long ms = (long) timeout.TotalMilliseconds;
  171. if (ms < -1 || ms > Int32.MaxValue)
  172. throw new ArgumentOutOfRangeException ("timeout");
  173. try {
  174. if (exitContext) SynchronizationAttribute.ExitContext ();
  175. return (WaitAny_internal(waitHandles, (int) ms, exitContext));
  176. }
  177. finally {
  178. if (exitContext) SynchronizationAttribute.EnterContext ();
  179. }
  180. }
  181. protected WaitHandle()
  182. {
  183. // FIXME
  184. }
  185. public virtual void Close() {
  186. Dispose(true);
  187. GC.SuppressFinalize (this);
  188. }
  189. public const int WaitTimeout = 258;
  190. //
  191. // In 2.0 we use SafeWaitHandles instead of IntPtrs
  192. //
  193. SafeWaitHandle safe_wait_handle;
  194. [Obsolete ("In the profiles > 2.x, use SafeHandle instead of Handle")]
  195. public virtual IntPtr Handle {
  196. get {
  197. return safe_wait_handle.DangerousGetHandle ();
  198. }
  199. [SecurityPermission (SecurityAction.LinkDemand, UnmanagedCode = true)]
  200. [SecurityPermission (SecurityAction.InheritanceDemand, UnmanagedCode = true)]
  201. set {
  202. if (value == InvalidHandle)
  203. safe_wait_handle = new SafeWaitHandle (InvalidHandle, false);
  204. else
  205. safe_wait_handle = new SafeWaitHandle (value, true);
  206. }
  207. }
  208. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  209. private extern bool WaitOne_internal(IntPtr handle, int ms, bool exitContext);
  210. protected virtual void Dispose (bool explicitDisposing)
  211. {
  212. if (!disposed){
  213. disposed = true;
  214. //
  215. // This is only the case if the handle was never properly initialized
  216. // most likely a bug in the derived class
  217. //
  218. if (safe_wait_handle == null)
  219. return;
  220. lock (this){
  221. if (safe_wait_handle != null)
  222. safe_wait_handle.Dispose ();
  223. }
  224. }
  225. }
  226. public SafeWaitHandle SafeWaitHandle {
  227. [ReliabilityContract (Consistency.WillNotCorruptState, Cer.MayFail)]
  228. get {
  229. return safe_wait_handle;
  230. }
  231. [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
  232. set {
  233. if (value == null)
  234. safe_wait_handle = new SafeWaitHandle (InvalidHandle, false);
  235. else
  236. safe_wait_handle = value;
  237. }
  238. }
  239. public static bool SignalAndWait (WaitHandle toSignal,
  240. WaitHandle toWaitOn)
  241. {
  242. return SignalAndWait (toSignal, toWaitOn, -1, false);
  243. }
  244. public static bool SignalAndWait (WaitHandle toSignal,
  245. WaitHandle toWaitOn,
  246. int millisecondsTimeout,
  247. bool exitContext)
  248. {
  249. if (toSignal == null)
  250. throw new ArgumentNullException ("toSignal");
  251. if (toWaitOn == null)
  252. throw new ArgumentNullException ("toWaitOn");
  253. if (millisecondsTimeout < -1)
  254. throw new ArgumentOutOfRangeException ("millisecondsTimeout");
  255. return SignalAndWait_Internal (toSignal.Handle, toWaitOn.Handle, millisecondsTimeout, exitContext);
  256. }
  257. public static bool SignalAndWait (WaitHandle toSignal,
  258. WaitHandle toWaitOn,
  259. TimeSpan timeout,
  260. bool exitContext)
  261. {
  262. double ms = timeout.TotalMilliseconds;
  263. if (ms > Int32.MaxValue)
  264. throw new ArgumentOutOfRangeException ("timeout");
  265. return SignalAndWait (toSignal, toWaitOn, Convert.ToInt32 (ms), false);
  266. }
  267. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  268. static extern bool SignalAndWait_Internal (IntPtr toSignal, IntPtr toWaitOn, int ms, bool exitContext);
  269. public virtual bool WaitOne()
  270. {
  271. CheckDisposed ();
  272. bool release = false;
  273. try {
  274. safe_wait_handle.DangerousAddRef (ref release);
  275. return (WaitOne_internal(safe_wait_handle.DangerousGetHandle (), Timeout.Infinite, false));
  276. } finally {
  277. if (release)
  278. safe_wait_handle.DangerousRelease ();
  279. }
  280. }
  281. public virtual bool WaitOne(int millisecondsTimeout, bool exitContext)
  282. {
  283. CheckDisposed ();
  284. // check negative - except for -1 (which is Timeout.Infinite)
  285. if (millisecondsTimeout < Timeout.Infinite)
  286. throw new ArgumentOutOfRangeException ("millisecondsTimeout");
  287. bool release = false;
  288. try {
  289. if (exitContext)
  290. SynchronizationAttribute.ExitContext ();
  291. safe_wait_handle.DangerousAddRef (ref release);
  292. return (WaitOne_internal(safe_wait_handle.DangerousGetHandle (), millisecondsTimeout, exitContext));
  293. } finally {
  294. if (exitContext)
  295. SynchronizationAttribute.EnterContext ();
  296. if (release)
  297. safe_wait_handle.DangerousRelease ();
  298. }
  299. }
  300. public virtual bool WaitOne (int millisecondsTimeout)
  301. {
  302. return WaitOne (millisecondsTimeout, false);
  303. }
  304. public virtual bool WaitOne (TimeSpan timeout)
  305. {
  306. return WaitOne (timeout, false);
  307. }
  308. public virtual bool WaitOne(TimeSpan timeout, bool exitContext)
  309. {
  310. CheckDisposed ();
  311. long ms = (long) timeout.TotalMilliseconds;
  312. if (ms < -1 || ms > Int32.MaxValue)
  313. throw new ArgumentOutOfRangeException ("timeout");
  314. bool release = false;
  315. try {
  316. if (exitContext)
  317. SynchronizationAttribute.ExitContext ();
  318. safe_wait_handle.DangerousAddRef (ref release);
  319. return (WaitOne_internal(safe_wait_handle.DangerousGetHandle (), (int) ms, exitContext));
  320. }
  321. finally {
  322. if (exitContext)
  323. SynchronizationAttribute.EnterContext ();
  324. if (release)
  325. safe_wait_handle.DangerousRelease ();
  326. }
  327. }
  328. internal void CheckDisposed ()
  329. {
  330. if (disposed || safe_wait_handle == null)
  331. throw new ObjectDisposedException (GetType ().FullName);
  332. }
  333. public static bool WaitAll(WaitHandle[] waitHandles, int millisecondsTimeout)
  334. {
  335. return WaitAll (waitHandles, millisecondsTimeout, false);
  336. }
  337. public static bool WaitAll(WaitHandle[] waitHandles, TimeSpan timeout)
  338. {
  339. return WaitAll (waitHandles, timeout, false);
  340. }
  341. protected static readonly IntPtr InvalidHandle = (IntPtr) (-1);
  342. bool disposed = false;
  343. void IDisposable.Dispose() {
  344. Dispose(true);
  345. // Take yourself off the Finalization queue
  346. GC.SuppressFinalize(this);
  347. }
  348. ~WaitHandle() {
  349. Dispose(false);
  350. }
  351. }
  352. }