WaitHandle.cs 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  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. #if !DISABLE_REMOTING
  34. using System.Runtime.Remoting.Contexts;
  35. #endif
  36. using System.Runtime.InteropServices;
  37. using Microsoft.Win32.SafeHandles;
  38. using System.Runtime.ConstrainedExecution;
  39. namespace System.Threading
  40. {
  41. [StructLayout (LayoutKind.Sequential)]
  42. public abstract partial class WaitHandle
  43. {
  44. protected static readonly IntPtr InvalidHandle = (IntPtr) (-1);
  45. internal const int MaxWaitHandles = 64;
  46. // We rely on the reference source implementation of WaitHandle, and it delegates to a function named
  47. // WaitOneNative to perform the actual operation of waiting on a handle.
  48. // This native operation actually has to call back into managed code and invoke .Wait
  49. // on the current SynchronizationContext. As such, our implementation of this "native" method
  50. // is actually managed code, and the real native icall being used is Wait_internal.
  51. static int WaitOneNative (SafeHandle waitableSafeHandle, uint millisecondsTimeout, bool hasThreadAffinity, bool exitContext)
  52. {
  53. bool release = false;
  54. #if !MONODROID
  55. var context = SynchronizationContext.Current;
  56. #endif
  57. try {
  58. waitableSafeHandle.DangerousAddRef (ref release);
  59. #if !DISABLE_REMOTING
  60. if (exitContext)
  61. SynchronizationAttribute.ExitContext ();
  62. #endif
  63. #if !MONODROID
  64. // HACK: Documentation (and public posts by experts like Joe Duffy) suggests that
  65. // users must first call SetWaitNotificationRequired to flag that a given synchronization
  66. // context overrides .Wait. Because invoking the Wait method is somewhat expensive, we use
  67. // the notification-required flag to determine whether or not we should invoke the managed
  68. // wait method.
  69. // Another option would be to check whether this context uses the default Wait implementation,
  70. // but I don't know of a cheap way to do this that handles derived types correctly.
  71. // If the thread does not have a synchronization context set at all, we can safely just
  72. // jump directly to invoking Wait_internal.
  73. if ((context != null) && context.IsWaitNotificationRequired ()) {
  74. return context.Wait (
  75. new IntPtr[] { waitableSafeHandle.DangerousGetHandle () },
  76. false,
  77. (int)millisecondsTimeout
  78. );
  79. } else
  80. #endif
  81. {
  82. unsafe {
  83. IntPtr handle = waitableSafeHandle.DangerousGetHandle ();
  84. return Wait_internal (&handle, 1, false, (int)millisecondsTimeout);
  85. }
  86. }
  87. } finally {
  88. if (release)
  89. waitableSafeHandle.DangerousRelease ();
  90. #if !DISABLE_REMOTING
  91. if (exitContext)
  92. SynchronizationAttribute.EnterContext ();
  93. #endif
  94. }
  95. }
  96. static int WaitMultiple(WaitHandle[] waitHandles, int millisecondsTimeout, bool exitContext, bool WaitAll)
  97. {
  98. if (waitHandles.Length > MaxWaitHandles)
  99. return WAIT_FAILED;
  100. int release_last = -1;
  101. var context = SynchronizationContext.Current;
  102. try {
  103. #if !DISABLE_REMOTING
  104. if (exitContext)
  105. SynchronizationAttribute.ExitContext ();
  106. #endif
  107. for (int i = 0; i < waitHandles.Length; ++i) {
  108. try {} finally {
  109. /* we have to put it in a finally block, to avoid having a ThreadAbortException
  110. * between the return from DangerousAddRef and the assignement to release_last */
  111. bool release = false;
  112. waitHandles [i].SafeWaitHandle.DangerousAddRef (ref release);
  113. release_last = i;
  114. }
  115. }
  116. if ((context != null) && context.IsWaitNotificationRequired ()) {
  117. IntPtr[] handles = new IntPtr[waitHandles.Length];
  118. for (int i = 0; i < waitHandles.Length; ++i)
  119. handles[i] = waitHandles[i].SafeWaitHandle.DangerousGetHandle ();
  120. return context.Wait (
  121. handles,
  122. false,
  123. (int)millisecondsTimeout
  124. );
  125. } else {
  126. unsafe {
  127. IntPtr* handles = stackalloc IntPtr[waitHandles.Length];
  128. for (int i = 0; i < waitHandles.Length; ++i)
  129. handles[i] = waitHandles[i].SafeWaitHandle.DangerousGetHandle ();
  130. return Wait_internal (handles, waitHandles.Length, WaitAll, millisecondsTimeout);
  131. }
  132. }
  133. } finally {
  134. for (int i = release_last; i >= 0; --i) {
  135. waitHandles [i].SafeWaitHandle.DangerousRelease ();
  136. }
  137. #if !DISABLE_REMOTING
  138. if (exitContext)
  139. SynchronizationAttribute.EnterContext ();
  140. #endif
  141. }
  142. }
  143. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  144. internal unsafe static extern int Wait_internal(IntPtr* handles, int numHandles, bool waitAll, int ms);
  145. static int SignalAndWaitOne (SafeWaitHandle waitHandleToSignal,SafeWaitHandle waitHandleToWaitOn, int millisecondsTimeout, bool hasThreadAffinity, bool exitContext)
  146. {
  147. bool releaseHandleToSignal = false, releaseHandleToWaitOn = false;
  148. try {
  149. waitHandleToSignal.DangerousAddRef (ref releaseHandleToSignal);
  150. waitHandleToWaitOn.DangerousAddRef (ref releaseHandleToWaitOn);
  151. return SignalAndWait_Internal (waitHandleToSignal.DangerousGetHandle (), waitHandleToWaitOn.DangerousGetHandle (), millisecondsTimeout);
  152. } finally {
  153. if (releaseHandleToSignal)
  154. waitHandleToSignal.DangerousRelease ();
  155. if (releaseHandleToWaitOn)
  156. waitHandleToWaitOn.DangerousRelease ();
  157. }
  158. }
  159. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  160. static extern int SignalAndWait_Internal (IntPtr toSignal, IntPtr toWaitOn, int ms);
  161. internal static int ToTimeoutMilliseconds(TimeSpan timeout)
  162. {
  163. var timeoutMilliseconds = (long)timeout.TotalMilliseconds;
  164. if (timeoutMilliseconds < -1 || timeoutMilliseconds > int.MaxValue)
  165. {
  166. throw new ArgumentOutOfRangeException(nameof(timeout), SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
  167. }
  168. return (int)timeoutMilliseconds;
  169. }
  170. }
  171. }