AsyncWaitHandle.cs 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  1. //----------------------------------------------------------------
  2. // Copyright (c) Microsoft Corporation. All rights reserved.
  3. //----------------------------------------------------------------
  4. namespace System.Runtime
  5. {
  6. using System;
  7. using System.Collections.Generic;
  8. using System.Security;
  9. using System.Threading;
  10. [Fx.Tag.SynchronizationPrimitive(Fx.Tag.BlocksUsing.MonitorWait, SupportsAsync = true, ReleaseMethod = "Set")]
  11. class AsyncWaitHandle
  12. {
  13. static Action<object> timerCompleteCallback;
  14. List<AsyncWaiter> asyncWaiters;
  15. bool isSignaled;
  16. EventResetMode resetMode;
  17. [Fx.Tag.SynchronizationObject(Kind = Fx.Tag.SynchronizationKind.MonitorWait)]
  18. object syncObject;
  19. int syncWaiterCount;
  20. public AsyncWaitHandle()
  21. : this(EventResetMode.AutoReset)
  22. {
  23. }
  24. public AsyncWaitHandle(EventResetMode resetMode)
  25. {
  26. this.resetMode = resetMode;
  27. this.syncObject = new object();
  28. }
  29. public bool WaitAsync(Action<object, TimeoutException> callback, object state, TimeSpan timeout)
  30. {
  31. if (!this.isSignaled || (this.isSignaled && this.resetMode == EventResetMode.AutoReset))
  32. {
  33. lock (syncObject)
  34. {
  35. if (this.isSignaled && this.resetMode == EventResetMode.AutoReset)
  36. {
  37. this.isSignaled = false;
  38. }
  39. else if (!this.isSignaled)
  40. {
  41. AsyncWaiter waiter = new AsyncWaiter(this, callback, state);
  42. if (this.asyncWaiters == null)
  43. {
  44. this.asyncWaiters = new List<AsyncWaiter>();
  45. }
  46. this.asyncWaiters.Add(waiter);
  47. if (timeout != TimeSpan.MaxValue)
  48. {
  49. if (timerCompleteCallback == null)
  50. {
  51. timerCompleteCallback = new Action<object>(OnTimerComplete);
  52. }
  53. waiter.SetTimer(timerCompleteCallback, waiter, timeout);
  54. }
  55. return false;
  56. }
  57. }
  58. }
  59. return true;
  60. }
  61. static void OnTimerComplete(object state)
  62. {
  63. AsyncWaiter waiter = (AsyncWaiter)state;
  64. AsyncWaitHandle thisPtr = waiter.Parent;
  65. bool callWaiter = false;
  66. lock (thisPtr.syncObject)
  67. {
  68. // If still in the waiting list (that means it hasn't been signaled)
  69. if (thisPtr.asyncWaiters != null && thisPtr.asyncWaiters.Remove(waiter))
  70. {
  71. waiter.TimedOut = true;
  72. callWaiter = true;
  73. }
  74. }
  75. waiter.CancelTimer();
  76. if (callWaiter)
  77. {
  78. waiter.Call();
  79. }
  80. }
  81. [Fx.Tag.Blocking]
  82. public bool Wait(TimeSpan timeout)
  83. {
  84. if (!this.isSignaled || (this.isSignaled && this.resetMode == EventResetMode.AutoReset))
  85. {
  86. lock (syncObject)
  87. {
  88. if (this.isSignaled && this.resetMode == EventResetMode.AutoReset)
  89. {
  90. this.isSignaled = false;
  91. }
  92. else if (!this.isSignaled)
  93. {
  94. bool decrementRequired = false;
  95. try
  96. {
  97. try
  98. {
  99. }
  100. finally
  101. {
  102. this.syncWaiterCount++;
  103. decrementRequired = true;
  104. }
  105. if (timeout == TimeSpan.MaxValue)
  106. {
  107. if (!Monitor.Wait(syncObject, Timeout.Infinite))
  108. {
  109. return false;
  110. }
  111. }
  112. else
  113. {
  114. if (!Monitor.Wait(syncObject, timeout))
  115. {
  116. return false;
  117. }
  118. }
  119. }
  120. finally
  121. {
  122. if (decrementRequired)
  123. {
  124. this.syncWaiterCount--;
  125. }
  126. }
  127. }
  128. }
  129. }
  130. return true;
  131. }
  132. public void Set()
  133. {
  134. List<AsyncWaiter> toCallList = null;
  135. AsyncWaiter toCall = null;
  136. if (!this.isSignaled)
  137. {
  138. lock (syncObject)
  139. {
  140. if (!this.isSignaled)
  141. {
  142. if (this.resetMode == EventResetMode.ManualReset)
  143. {
  144. this.isSignaled = true;
  145. Monitor.PulseAll(syncObject);
  146. toCallList = this.asyncWaiters;
  147. this.asyncWaiters = null;
  148. }
  149. else
  150. {
  151. if (this.syncWaiterCount > 0)
  152. {
  153. Monitor.Pulse(syncObject);
  154. }
  155. else if (this.asyncWaiters != null && this.asyncWaiters.Count > 0)
  156. {
  157. toCall = this.asyncWaiters[0];
  158. this.asyncWaiters.RemoveAt(0);
  159. }
  160. else
  161. {
  162. this.isSignaled = true;
  163. }
  164. }
  165. }
  166. }
  167. }
  168. if (toCallList != null)
  169. {
  170. foreach (AsyncWaiter waiter in toCallList)
  171. {
  172. waiter.CancelTimer();
  173. waiter.Call();
  174. }
  175. }
  176. if (toCall != null)
  177. {
  178. toCall.CancelTimer();
  179. toCall.Call();
  180. }
  181. }
  182. public void Reset()
  183. {
  184. // Doesn't matter if this changes during processing of another method
  185. this.isSignaled = false;
  186. }
  187. class AsyncWaiter : ActionItem
  188. {
  189. [Fx.Tag.SecurityNote(Critical = "Store the delegate to be invoked")]
  190. [SecurityCritical]
  191. Action<object, TimeoutException> callback;
  192. [Fx.Tag.SecurityNote(Critical = "Stores the state object to be passed to the callback")]
  193. [SecurityCritical]
  194. object state;
  195. IOThreadTimer timer;
  196. TimeSpan originalTimeout;
  197. [Fx.Tag.SecurityNote(Critical = "Access critical members", Safe = "Doesn't leak information")]
  198. [SecuritySafeCritical]
  199. public AsyncWaiter(AsyncWaitHandle parent, Action<object, TimeoutException> callback, object state)
  200. {
  201. this.Parent = parent;
  202. this.callback = callback;
  203. this.state = state;
  204. }
  205. public AsyncWaitHandle Parent
  206. {
  207. get;
  208. private set;
  209. }
  210. public bool TimedOut
  211. {
  212. get;
  213. set;
  214. }
  215. [Fx.Tag.SecurityNote(Critical = "Calls into critical method Schedule", Safe = "Invokes the given delegate under the current context")]
  216. [SecuritySafeCritical]
  217. public void Call()
  218. {
  219. Schedule();
  220. }
  221. [Fx.Tag.SecurityNote(Critical = "Overriding an inherited critical method, access critical members")]
  222. [SecurityCritical]
  223. protected override void Invoke()
  224. {
  225. this.callback(this.state,
  226. this.TimedOut ? new TimeoutException(InternalSR.TimeoutOnOperation(this.originalTimeout)) : null);
  227. }
  228. public void SetTimer(Action<object> callback, object state, TimeSpan timeout)
  229. {
  230. if (this.timer != null)
  231. {
  232. throw Fx.Exception.AsError(new InvalidOperationException(InternalSR.MustCancelOldTimer));
  233. }
  234. this.originalTimeout = timeout;
  235. this.timer = new IOThreadTimer(callback, state, false);
  236. this.timer.Set(timeout);
  237. }
  238. public void CancelTimer()
  239. {
  240. if (this.timer != null)
  241. {
  242. this.timer.Cancel();
  243. this.timer = null;
  244. }
  245. }
  246. }
  247. }
  248. }