AsyncResult.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) Microsoft Corporation. All rights reserved.
  3. //-----------------------------------------------------------------------------
  4. namespace System.Runtime
  5. {
  6. using System;
  7. using System.Diagnostics;
  8. using System.Diagnostics.CodeAnalysis;
  9. using System.Threading;
  10. // AsyncResult starts acquired; Complete releases.
  11. [Fx.Tag.SynchronizationPrimitive(Fx.Tag.BlocksUsing.ManualResetEvent, SupportsAsync = true, ReleaseMethod = "Complete")]
  12. abstract class AsyncResult : IAsyncResult
  13. {
  14. static AsyncCallback asyncCompletionWrapperCallback;
  15. AsyncCallback callback;
  16. bool completedSynchronously;
  17. bool endCalled;
  18. Exception exception;
  19. bool isCompleted;
  20. AsyncCompletion nextAsyncCompletion;
  21. object state;
  22. Action beforePrepareAsyncCompletionAction;
  23. Func<IAsyncResult, bool> checkSyncValidationFunc;
  24. [Fx.Tag.SynchronizationObject]
  25. ManualResetEvent manualResetEvent;
  26. [Fx.Tag.SynchronizationObject(Blocking = false)]
  27. object thisLock;
  28. #if DEBUG
  29. StackTrace endStack;
  30. StackTrace completeStack;
  31. UncompletedAsyncResultMarker marker;
  32. #endif
  33. protected AsyncResult(AsyncCallback callback, object state)
  34. {
  35. this.callback = callback;
  36. this.state = state;
  37. this.thisLock = new object();
  38. #if DEBUG
  39. this.marker = new UncompletedAsyncResultMarker(this);
  40. #endif
  41. }
  42. public object AsyncState
  43. {
  44. get
  45. {
  46. return state;
  47. }
  48. }
  49. public WaitHandle AsyncWaitHandle
  50. {
  51. get
  52. {
  53. if (manualResetEvent != null)
  54. {
  55. return manualResetEvent;
  56. }
  57. lock (ThisLock)
  58. {
  59. if (manualResetEvent == null)
  60. {
  61. manualResetEvent = new ManualResetEvent(isCompleted);
  62. }
  63. }
  64. return manualResetEvent;
  65. }
  66. }
  67. public bool CompletedSynchronously
  68. {
  69. get
  70. {
  71. return completedSynchronously;
  72. }
  73. }
  74. public bool HasCallback
  75. {
  76. get
  77. {
  78. return this.callback != null;
  79. }
  80. }
  81. public bool IsCompleted
  82. {
  83. get
  84. {
  85. return isCompleted;
  86. }
  87. }
  88. // used in conjunction with PrepareAsyncCompletion to allow for finally blocks
  89. protected Action<AsyncResult, Exception> OnCompleting { get; set; }
  90. object ThisLock
  91. {
  92. get
  93. {
  94. return this.thisLock;
  95. }
  96. }
  97. // subclasses like TraceAsyncResult can use this to wrap the callback functionality in a scope
  98. protected Action<AsyncCallback, IAsyncResult> VirtualCallback
  99. {
  100. get;
  101. set;
  102. }
  103. protected void Complete(bool completedSynchronously)
  104. {
  105. if (this.isCompleted)
  106. {
  107. throw Fx.Exception.AsError(new InvalidOperationException(InternalSR.AsyncResultCompletedTwice(GetType())));
  108. }
  109. #if DEBUG
  110. this.marker.AsyncResult = null;
  111. this.marker = null;
  112. if (!Fx.FastDebug && completeStack == null)
  113. {
  114. completeStack = new StackTrace();
  115. }
  116. #endif
  117. this.completedSynchronously = completedSynchronously;
  118. if (OnCompleting != null)
  119. {
  120. // Allow exception replacement, like a catch/throw pattern.
  121. try
  122. {
  123. OnCompleting(this, this.exception);
  124. }
  125. catch (Exception exception)
  126. {
  127. if (Fx.IsFatal(exception))
  128. {
  129. throw;
  130. }
  131. this.exception = exception;
  132. }
  133. }
  134. if (completedSynchronously)
  135. {
  136. // If we completedSynchronously, then there's no chance that the manualResetEvent was created so
  137. // we don't need to worry about a ----
  138. Fx.Assert(this.manualResetEvent == null, "No ManualResetEvent should be created for a synchronous AsyncResult.");
  139. this.isCompleted = true;
  140. }
  141. else
  142. {
  143. lock (ThisLock)
  144. {
  145. this.isCompleted = true;
  146. if (this.manualResetEvent != null)
  147. {
  148. this.manualResetEvent.Set();
  149. }
  150. }
  151. }
  152. if (this.callback != null)
  153. {
  154. try
  155. {
  156. if (VirtualCallback != null)
  157. {
  158. VirtualCallback(this.callback, this);
  159. }
  160. else
  161. {
  162. this.callback(this);
  163. }
  164. }
  165. #pragma warning disable 1634
  166. #pragma warning suppress 56500 // transferring exception to another thread
  167. catch (Exception e)
  168. {
  169. if (Fx.IsFatal(e))
  170. {
  171. throw;
  172. }
  173. throw Fx.Exception.AsError(new CallbackException(InternalSR.AsyncCallbackThrewException, e));
  174. }
  175. #pragma warning restore 1634
  176. }
  177. }
  178. protected void Complete(bool completedSynchronously, Exception exception)
  179. {
  180. this.exception = exception;
  181. Complete(completedSynchronously);
  182. }
  183. static void AsyncCompletionWrapperCallback(IAsyncResult result)
  184. {
  185. if (result == null)
  186. {
  187. throw Fx.Exception.AsError(new InvalidOperationException(InternalSR.InvalidNullAsyncResult));
  188. }
  189. if (result.CompletedSynchronously)
  190. {
  191. return;
  192. }
  193. AsyncResult thisPtr = (AsyncResult)result.AsyncState;
  194. if (!thisPtr.OnContinueAsyncCompletion(result))
  195. {
  196. return;
  197. }
  198. AsyncCompletion callback = thisPtr.GetNextCompletion();
  199. if (callback == null)
  200. {
  201. ThrowInvalidAsyncResult(result);
  202. }
  203. bool completeSelf = false;
  204. Exception completionException = null;
  205. try
  206. {
  207. completeSelf = callback(result);
  208. }
  209. catch (Exception e)
  210. {
  211. if (Fx.IsFatal(e))
  212. {
  213. throw;
  214. }
  215. completeSelf = true;
  216. completionException = e;
  217. }
  218. if (completeSelf)
  219. {
  220. thisPtr.Complete(false, completionException);
  221. }
  222. }
  223. // Note: this should be only derived by the TransactedAsyncResult
  224. protected virtual bool OnContinueAsyncCompletion(IAsyncResult result)
  225. {
  226. return true;
  227. }
  228. // Note: this should be used only by the TransactedAsyncResult
  229. protected void SetBeforePrepareAsyncCompletionAction(Action beforePrepareAsyncCompletionAction)
  230. {
  231. this.beforePrepareAsyncCompletionAction = beforePrepareAsyncCompletionAction;
  232. }
  233. // Note: this should be used only by the TransactedAsyncResult
  234. protected void SetCheckSyncValidationFunc(Func<IAsyncResult, bool> checkSyncValidationFunc)
  235. {
  236. this.checkSyncValidationFunc = checkSyncValidationFunc;
  237. }
  238. protected AsyncCallback PrepareAsyncCompletion(AsyncCompletion callback)
  239. {
  240. if (this.beforePrepareAsyncCompletionAction != null)
  241. {
  242. this.beforePrepareAsyncCompletionAction();
  243. }
  244. this.nextAsyncCompletion = callback;
  245. if (AsyncResult.asyncCompletionWrapperCallback == null)
  246. {
  247. AsyncResult.asyncCompletionWrapperCallback = Fx.ThunkCallback(new AsyncCallback(AsyncCompletionWrapperCallback));
  248. }
  249. return AsyncResult.asyncCompletionWrapperCallback;
  250. }
  251. protected bool CheckSyncContinue(IAsyncResult result)
  252. {
  253. AsyncCompletion dummy;
  254. return TryContinueHelper(result, out dummy);
  255. }
  256. protected bool SyncContinue(IAsyncResult result)
  257. {
  258. AsyncCompletion callback;
  259. if (TryContinueHelper(result, out callback))
  260. {
  261. return callback(result);
  262. }
  263. else
  264. {
  265. return false;
  266. }
  267. }
  268. bool TryContinueHelper(IAsyncResult result, out AsyncCompletion callback)
  269. {
  270. if (result == null)
  271. {
  272. throw Fx.Exception.AsError(new InvalidOperationException(InternalSR.InvalidNullAsyncResult));
  273. }
  274. callback = null;
  275. if (this.checkSyncValidationFunc != null)
  276. {
  277. if (!this.checkSyncValidationFunc(result))
  278. {
  279. return false;
  280. }
  281. }
  282. else if (!result.CompletedSynchronously)
  283. {
  284. return false;
  285. }
  286. callback = GetNextCompletion();
  287. if (callback == null)
  288. {
  289. ThrowInvalidAsyncResult("Only call Check/SyncContinue once per async operation (once per PrepareAsyncCompletion).");
  290. }
  291. return true;
  292. }
  293. AsyncCompletion GetNextCompletion()
  294. {
  295. AsyncCompletion result = this.nextAsyncCompletion;
  296. this.nextAsyncCompletion = null;
  297. return result;
  298. }
  299. protected static void ThrowInvalidAsyncResult(IAsyncResult result)
  300. {
  301. throw Fx.Exception.AsError(new InvalidOperationException(InternalSR.InvalidAsyncResultImplementation(result.GetType())));
  302. }
  303. protected static void ThrowInvalidAsyncResult(string debugText)
  304. {
  305. string message = InternalSR.InvalidAsyncResultImplementationGeneric;
  306. if (debugText != null)
  307. {
  308. #if DEBUG
  309. message += " " + debugText;
  310. #endif
  311. }
  312. throw Fx.Exception.AsError(new InvalidOperationException(message));
  313. }
  314. [Fx.Tag.Blocking(Conditional = "!asyncResult.isCompleted")]
  315. protected static TAsyncResult End<TAsyncResult>(IAsyncResult result)
  316. where TAsyncResult : AsyncResult
  317. {
  318. if (result == null)
  319. {
  320. throw Fx.Exception.ArgumentNull("result");
  321. }
  322. TAsyncResult asyncResult = result as TAsyncResult;
  323. if (asyncResult == null)
  324. {
  325. throw Fx.Exception.Argument("result", InternalSR.InvalidAsyncResult);
  326. }
  327. if (asyncResult.endCalled)
  328. {
  329. throw Fx.Exception.AsError(new InvalidOperationException(InternalSR.AsyncResultAlreadyEnded));
  330. }
  331. #if DEBUG
  332. if (!Fx.FastDebug && asyncResult.endStack == null)
  333. {
  334. asyncResult.endStack = new StackTrace();
  335. }
  336. #endif
  337. asyncResult.endCalled = true;
  338. if (!asyncResult.isCompleted)
  339. {
  340. asyncResult.AsyncWaitHandle.WaitOne();
  341. }
  342. if (asyncResult.manualResetEvent != null)
  343. {
  344. asyncResult.manualResetEvent.Close();
  345. }
  346. if (asyncResult.exception != null)
  347. {
  348. throw Fx.Exception.AsError(asyncResult.exception);
  349. }
  350. return asyncResult;
  351. }
  352. // can be utilized by subclasses to write core completion code for both the [....] and async paths
  353. // in one location, signalling chainable synchronous completion with the boolean result,
  354. // and leveraging PrepareAsyncCompletion for conversion to an AsyncCallback.
  355. // NOTE: requires that "this" is passed in as the state object to the asynchronous sub-call being used with a completion routine.
  356. protected delegate bool AsyncCompletion(IAsyncResult result);
  357. #if DEBUG
  358. class UncompletedAsyncResultMarker
  359. {
  360. public UncompletedAsyncResultMarker(AsyncResult result)
  361. {
  362. AsyncResult = result;
  363. }
  364. [SuppressMessage(FxCop.Category.Performance, FxCop.Rule.AvoidUncalledPrivateCode,
  365. Justification = "Debug-only facility")]
  366. public AsyncResult AsyncResult { get; set; }
  367. }
  368. #endif
  369. }
  370. }