WaitHandle.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  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. #if NET_4_0
  190. public void Dispose ()
  191. {
  192. Close ();
  193. }
  194. #endif
  195. public const int WaitTimeout = 258;
  196. //
  197. // In 2.0 we use SafeWaitHandles instead of IntPtrs
  198. //
  199. SafeWaitHandle safe_wait_handle;
  200. [Obsolete ("In the profiles > 2.x, use SafeHandle instead of Handle")]
  201. public virtual IntPtr Handle {
  202. get {
  203. return safe_wait_handle.DangerousGetHandle ();
  204. }
  205. [SecurityPermission (SecurityAction.LinkDemand, UnmanagedCode = true)]
  206. [SecurityPermission (SecurityAction.InheritanceDemand, UnmanagedCode = true)]
  207. set {
  208. if (value == InvalidHandle)
  209. safe_wait_handle = new SafeWaitHandle (InvalidHandle, false);
  210. else
  211. safe_wait_handle = new SafeWaitHandle (value, true);
  212. }
  213. }
  214. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  215. private extern bool WaitOne_internal(IntPtr handle, int ms, bool exitContext);
  216. protected virtual void Dispose (bool explicitDisposing)
  217. {
  218. if (!disposed){
  219. disposed = true;
  220. //
  221. // This is only the case if the handle was never properly initialized
  222. // most likely a bug in the derived class
  223. //
  224. if (safe_wait_handle == null)
  225. return;
  226. lock (this){
  227. if (safe_wait_handle != null)
  228. safe_wait_handle.Dispose ();
  229. }
  230. }
  231. }
  232. public SafeWaitHandle SafeWaitHandle {
  233. [ReliabilityContract (Consistency.WillNotCorruptState, Cer.MayFail)]
  234. get {
  235. return safe_wait_handle;
  236. }
  237. [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
  238. set {
  239. if (value == null)
  240. safe_wait_handle = new SafeWaitHandle (InvalidHandle, false);
  241. else
  242. safe_wait_handle = value;
  243. }
  244. }
  245. public static bool SignalAndWait (WaitHandle toSignal,
  246. WaitHandle toWaitOn)
  247. {
  248. return SignalAndWait (toSignal, toWaitOn, -1, false);
  249. }
  250. public static bool SignalAndWait (WaitHandle toSignal,
  251. WaitHandle toWaitOn,
  252. int millisecondsTimeout,
  253. bool exitContext)
  254. {
  255. if (toSignal == null)
  256. throw new ArgumentNullException ("toSignal");
  257. if (toWaitOn == null)
  258. throw new ArgumentNullException ("toWaitOn");
  259. if (millisecondsTimeout < -1)
  260. throw new ArgumentOutOfRangeException ("millisecondsTimeout");
  261. return SignalAndWait_Internal (toSignal.Handle, toWaitOn.Handle, millisecondsTimeout, exitContext);
  262. }
  263. public static bool SignalAndWait (WaitHandle toSignal,
  264. WaitHandle toWaitOn,
  265. TimeSpan timeout,
  266. bool exitContext)
  267. {
  268. double ms = timeout.TotalMilliseconds;
  269. if (ms > Int32.MaxValue)
  270. throw new ArgumentOutOfRangeException ("timeout");
  271. return SignalAndWait (toSignal, toWaitOn, Convert.ToInt32 (ms), false);
  272. }
  273. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  274. static extern bool SignalAndWait_Internal (IntPtr toSignal, IntPtr toWaitOn, int ms, bool exitContext);
  275. public virtual bool WaitOne()
  276. {
  277. CheckDisposed ();
  278. bool release = false;
  279. try {
  280. safe_wait_handle.DangerousAddRef (ref release);
  281. return (WaitOne_internal(safe_wait_handle.DangerousGetHandle (), Timeout.Infinite, false));
  282. } finally {
  283. if (release)
  284. safe_wait_handle.DangerousRelease ();
  285. }
  286. }
  287. public virtual bool WaitOne(int millisecondsTimeout, bool exitContext)
  288. {
  289. CheckDisposed ();
  290. // check negative - except for -1 (which is Timeout.Infinite)
  291. if (millisecondsTimeout < Timeout.Infinite)
  292. throw new ArgumentOutOfRangeException ("millisecondsTimeout");
  293. bool release = false;
  294. try {
  295. if (exitContext)
  296. SynchronizationAttribute.ExitContext ();
  297. safe_wait_handle.DangerousAddRef (ref release);
  298. return (WaitOne_internal(safe_wait_handle.DangerousGetHandle (), millisecondsTimeout, exitContext));
  299. } finally {
  300. if (exitContext)
  301. SynchronizationAttribute.EnterContext ();
  302. if (release)
  303. safe_wait_handle.DangerousRelease ();
  304. }
  305. }
  306. public virtual bool WaitOne (int millisecondsTimeout)
  307. {
  308. return WaitOne (millisecondsTimeout, false);
  309. }
  310. public virtual bool WaitOne (TimeSpan timeout)
  311. {
  312. return WaitOne (timeout, false);
  313. }
  314. public virtual bool WaitOne(TimeSpan timeout, bool exitContext)
  315. {
  316. CheckDisposed ();
  317. long ms = (long) timeout.TotalMilliseconds;
  318. if (ms < -1 || ms > Int32.MaxValue)
  319. throw new ArgumentOutOfRangeException ("timeout");
  320. bool release = false;
  321. try {
  322. if (exitContext)
  323. SynchronizationAttribute.ExitContext ();
  324. safe_wait_handle.DangerousAddRef (ref release);
  325. return (WaitOne_internal(safe_wait_handle.DangerousGetHandle (), (int) ms, exitContext));
  326. }
  327. finally {
  328. if (exitContext)
  329. SynchronizationAttribute.EnterContext ();
  330. if (release)
  331. safe_wait_handle.DangerousRelease ();
  332. }
  333. }
  334. internal void CheckDisposed ()
  335. {
  336. if (disposed || safe_wait_handle == null)
  337. throw new ObjectDisposedException (GetType ().FullName);
  338. }
  339. public static bool WaitAll(WaitHandle[] waitHandles, int millisecondsTimeout)
  340. {
  341. return WaitAll (waitHandles, millisecondsTimeout, false);
  342. }
  343. public static bool WaitAll(WaitHandle[] waitHandles, TimeSpan timeout)
  344. {
  345. return WaitAll (waitHandles, timeout, false);
  346. }
  347. protected static readonly IntPtr InvalidHandle = (IntPtr) (-1);
  348. bool disposed = false;
  349. void IDisposable.Dispose() {
  350. Dispose(true);
  351. // Take yourself off the Finalization queue
  352. GC.SuppressFinalize(this);
  353. }
  354. ~WaitHandle() {
  355. Dispose(false);
  356. }
  357. }
  358. }