2
0

WaitHandle.cs 12 KB

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