WaitHandle.cs 12 KB

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