AsyncObservableMethodBuilder.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the MIT License.
  3. // See the LICENSE file in the project root for more information.
  4. using System.Reactive.Concurrency;
  5. using System.Reactive.Disposables;
  6. using System.Reactive.Subjects;
  7. using System.Runtime.ExceptionServices;
  8. using System.Security;
  9. using System.Threading.Tasks;
  10. namespace System.Runtime.CompilerServices
  11. {
  12. /// <summary>
  13. /// Represents a builder for asynchronous methods that return a task-like <see cref="IAsyncObservable{T}"/>.
  14. /// </summary>
  15. /// <typeparam name="T">The type of the elements in the sequence.</typeparam>
  16. public struct AsyncObservableMethodBuilder<T>
  17. {
  18. /// <summary>
  19. /// The compiler-generated asynchronous state machine representing the execution flow of the asynchronous
  20. /// method whose return type is a task-like <see cref="IAsyncObservable{T}"/>.
  21. /// </summary>
  22. private IAsyncStateMachine _stateMachine;
  23. /// <summary>
  24. /// The underlying observable sequence representing the result produced by the asynchronous method.
  25. /// </summary>
  26. private TaskObservable _inner;
  27. /// <summary>
  28. /// Creates an instance of the <see cref="AsyncObservableMethodBuilder{T}"/> struct.
  29. /// </summary>
  30. /// <returns>A new instance of the struct.</returns>
  31. public static AsyncObservableMethodBuilder<T> Create() => default(AsyncObservableMethodBuilder<T>);
  32. /// <summary>
  33. /// Begins running the builder with the associated state machine.
  34. /// </summary>
  35. /// <typeparam name="TStateMachine">The type of the state machine.</typeparam>
  36. /// <param name="stateMachine">The state machine instance, passed by reference.</param>
  37. /// <exception cref="ArgumentNullException"><paramref name="stateMachine"/> is <c>null</c>.</exception>
  38. public void Start<TStateMachine>(ref TStateMachine stateMachine)
  39. where TStateMachine : IAsyncStateMachine
  40. {
  41. if (stateMachine == null)
  42. throw new ArgumentNullException(nameof(stateMachine));
  43. stateMachine.MoveNext();
  44. }
  45. /// <summary>
  46. /// Associates the builder with the specified state machine.
  47. /// </summary>
  48. /// <param name="stateMachine">The state machine instance to associate with the builder.</param>
  49. /// <exception cref="ArgumentNullException"><paramref name="stateMachine"/> is <c>null</c>.</exception>
  50. /// <exception cref="InvalidOperationException">The state machine was previously set.</exception>
  51. public void SetStateMachine(IAsyncStateMachine stateMachine)
  52. {
  53. if (stateMachine == null)
  54. throw new ArgumentNullException(nameof(stateMachine));
  55. if (_stateMachine != null)
  56. throw new InvalidOperationException();
  57. _stateMachine = stateMachine;
  58. }
  59. /// <summary>
  60. /// Marks the observable as successfully completed.
  61. /// </summary>
  62. /// <param name="result">The result to use to complete the observable sequence.</param>
  63. /// <exception cref="InvalidOperationException">The observable has already completed.</exception>
  64. public void SetResult(T result)
  65. {
  66. if (_inner == null)
  67. {
  68. _inner = new TaskObservable(result);
  69. }
  70. else
  71. {
  72. _inner.SetResult(result);
  73. }
  74. }
  75. /// <summary>
  76. /// Marks the observable as failed and binds the specified exception to the observable sequence.
  77. /// </summary>
  78. /// <param name="exception">The exception to bind to the observable sequence.</param>
  79. /// <exception cref="ArgumentNullException"><paramref name="exception"/> is <c>null</c>.</exception>
  80. /// <exception cref="InvalidOperationException">The observable has already completed.</exception>
  81. public void SetException(Exception exception)
  82. {
  83. if (exception == null)
  84. throw new ArgumentNullException(nameof(exception));
  85. if (_inner == null)
  86. {
  87. _inner = new TaskObservable(exception);
  88. }
  89. else
  90. {
  91. _inner.SetException(exception);
  92. }
  93. }
  94. /// <summary>
  95. /// Gets the observable sequence for this builder.
  96. /// </summary>
  97. public IAsyncObservable<T> Task => _inner ?? (_inner = new TaskObservable());
  98. /// <summary>
  99. /// Schedules the state machine to proceed to the next action when the specified awaiter completes.
  100. /// </summary>
  101. /// <typeparam name="TAwaiter">The type of the awaiter.</typeparam>
  102. /// <typeparam name="TStateMachine">The type of the state machine.</typeparam>
  103. /// <param name="awaiter">The awaiter.</param>
  104. /// <param name="stateMachine">The state machine.</param>
  105. public void AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine)
  106. where TAwaiter : INotifyCompletion
  107. where TStateMachine : IAsyncStateMachine
  108. {
  109. try
  110. {
  111. if (_stateMachine == null)
  112. {
  113. var ignored = Task; // NB: Ensure we have the observable backed by an async subject ready.
  114. _stateMachine = stateMachine;
  115. _stateMachine.SetStateMachine(_stateMachine);
  116. }
  117. // NB: Rx has historically not bothered with execution contexts, so we don't do it here either.
  118. awaiter.OnCompleted(_stateMachine.MoveNext);
  119. }
  120. catch (Exception ex)
  121. {
  122. // NB: Prevent reentrancy into the async state machine when an exception would be observed
  123. // by the caller. This could cause concurrent execution of the async method. Instead,
  124. // rethrow the exception elsewhere.
  125. Rethrow(ex);
  126. }
  127. }
  128. /// <summary>
  129. /// Schedules the state machine to proceed to the next action when the specified awaiter completes.
  130. /// </summary>
  131. /// <typeparam name="TAwaiter">The type of the awaiter.</typeparam>
  132. /// <typeparam name="TStateMachine">The type of the state machine.</typeparam>
  133. /// <param name="awaiter">The awaiter.</param>
  134. /// <param name="stateMachine">The state machine.</param>
  135. [SecuritySafeCritical]
  136. public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine)
  137. where TAwaiter : ICriticalNotifyCompletion
  138. where TStateMachine : IAsyncStateMachine
  139. {
  140. try
  141. {
  142. if (_stateMachine == null)
  143. {
  144. var ignored = Task; // NB: Ensure we have the observable backed by an async subject ready.
  145. _stateMachine = stateMachine;
  146. _stateMachine.SetStateMachine(_stateMachine);
  147. }
  148. // NB: Rx has historically not bothered with execution contexts, so we don't do it here either.
  149. awaiter.UnsafeOnCompleted(_stateMachine.MoveNext);
  150. }
  151. catch (Exception ex)
  152. {
  153. // NB: Prevent reentrancy into the async state machine when an exception would be observed
  154. // by the caller. This could cause concurrent execution of the async method. Instead,
  155. // rethrow the exception elsewhere.
  156. Rethrow(ex);
  157. }
  158. }
  159. /// <summary>
  160. /// Rethrows an exception that was thrown from an awaiter's OnCompleted methods.
  161. /// </summary>
  162. /// <param name="exception">The exception to rethrow.</param>
  163. private static void Rethrow(Exception exception)
  164. {
  165. TaskPoolAsyncScheduler.Default.ScheduleAsync(_ =>
  166. {
  167. ExceptionDispatchInfo.Capture(exception).Throw();
  168. return System.Threading.Tasks.Task.CompletedTask;
  169. });
  170. }
  171. /// <summary>
  172. /// Implementation of the IObservable&lt;T&gt; interface compatible with async method return types.
  173. /// </summary>
  174. /// <remarks>
  175. /// This class implements a "task-like" type that can be used as the return type of an asynchronous
  176. /// method in C# 7.0 and beyond. For example:
  177. /// <code>
  178. /// async Observable&lt;int&gt; RxAsync()
  179. /// {
  180. /// var res = await Observable.Return(21).Delay(TimeSpan.FromSeconds(1));
  181. /// return res * 2;
  182. /// }
  183. /// </code>
  184. /// </remarks>
  185. /// <typeparam name="T">The type of the elements in the sequence.</typeparam>
  186. internal sealed class TaskObservable : IAsyncObservable<T>, INotifyCompletion
  187. {
  188. /// <summary>
  189. /// The underlying observable sequence to subscribe to in case the asynchronous method did not
  190. /// finish synchronously.
  191. /// </summary>
  192. private readonly AsyncAsyncSubject<T> _subject;
  193. /// <summary>
  194. /// The result returned by the asynchronous method in case the method finished synchronously.
  195. /// </summary>
  196. private readonly T _result;
  197. /// <summary>
  198. /// The exception thrown by the asynchronous method in case the method finished synchronously.
  199. /// </summary>
  200. private readonly Exception _exception;
  201. /// <summary>
  202. /// Creates a new <see cref="TaskObservable"/> for an asynchronous method that has not finished yet.
  203. /// </summary>
  204. public TaskObservable()
  205. {
  206. _subject = new SequentialAsyncAsyncSubject<T>();
  207. }
  208. /// <summary>
  209. /// Creates a new <see cref="TaskObservable"/> for an asynchronous method that synchronously returned
  210. /// the specified <paramref name="result"/> value.
  211. /// </summary>
  212. /// <param name="result">The result returned by the asynchronous method.</param>
  213. public TaskObservable(T result)
  214. {
  215. _result = result;
  216. }
  217. /// <summary>
  218. /// Creates a new <see cref="TaskObservable"/> for an asynchronous method that synchronously threw
  219. /// the specified <paramref name="exception"/>.
  220. /// </summary>
  221. /// <param name="exception">The exception thrown by the asynchronous method.</param>
  222. public TaskObservable(Exception exception)
  223. {
  224. _exception = exception;
  225. }
  226. /// <summary>
  227. /// Marks the observable as successfully completed.
  228. /// </summary>
  229. /// <param name="result">The result to use to complete the observable sequence.</param>
  230. /// <exception cref="InvalidOperationException">The observable has already completed.</exception>
  231. public async void SetResult(T result)
  232. {
  233. if (IsCompleted)
  234. throw new InvalidOperationException();
  235. // REVIEW: Async void method.
  236. await _subject.OnNextAsync(result).ConfigureAwait(false);
  237. await _subject.OnCompletedAsync().ConfigureAwait(false);
  238. }
  239. /// <summary>
  240. /// Marks the observable as failed and binds the specified exception to the observable sequence.
  241. /// </summary>
  242. /// <param name="exception">The exception to bind to the observable sequence.</param>
  243. /// <exception cref="ArgumentNullException"><paramref name="exception"/> is <c>null</c>.</exception>
  244. /// <exception cref="InvalidOperationException">The observable has already completed.</exception>
  245. public void SetException(Exception exception)
  246. {
  247. if (IsCompleted)
  248. throw new InvalidOperationException();
  249. _subject.OnErrorAsync(exception);
  250. }
  251. /// <summary>
  252. /// Subscribes the given observer to the observable sequence.
  253. /// </summary>
  254. /// <param name="observer">Observer that will receive notifications from the observable sequence.</param>
  255. /// <returns>Disposable object representing an observer's subscription to the observable sequence.</returns>
  256. /// <exception cref="ArgumentNullException"><paramref name="observer"/> is null.</exception>
  257. public ValueTask<IAsyncDisposable> SubscribeAsync(IAsyncObserver<T> observer)
  258. {
  259. if (_subject != null)
  260. {
  261. return _subject.SubscribeAsync(observer);
  262. }
  263. async ValueTask<IAsyncDisposable> CoreAsync()
  264. {
  265. if (_exception != null)
  266. {
  267. await observer.OnErrorAsync(_exception).ConfigureAwait(false);
  268. }
  269. else
  270. {
  271. await observer.OnNextAsync(_result).ConfigureAwait(false);
  272. }
  273. return AsyncDisposable.Nop;
  274. }
  275. return CoreAsync();
  276. }
  277. /// <summary>
  278. /// Gets an awaiter that can be used to await the eventual completion of the observable sequence.
  279. /// </summary>
  280. /// <returns>An awaiter that can be used to await the eventual completion of the observable sequence.</returns>
  281. public AsyncAsyncSubject<T> GetAwaiter() => _subject;
  282. /// <summary>
  283. /// Gets a Boolean indicating whether the observable sequence has completed.
  284. /// </summary>
  285. public bool IsCompleted => _subject?.IsCompleted ?? true;
  286. /// <summary>
  287. /// Gets the result produced by the observable sequence.
  288. /// </summary>
  289. /// <returns>The result produced by the observable sequence.</returns>
  290. public T GetResult()
  291. {
  292. if (_subject != null)
  293. {
  294. return _subject.GetResult();
  295. }
  296. if (_exception != null)
  297. {
  298. ExceptionDispatchInfo.Capture(_exception).Throw();
  299. }
  300. return _result;
  301. }
  302. /// <summary>
  303. /// Attaches the specified <paramref name="continuation"/> to the observable sequence.
  304. /// </summary>
  305. /// <param name="continuation">The continuation to attach.</param>
  306. public void OnCompleted(Action continuation)
  307. {
  308. if (_subject != null)
  309. {
  310. _subject.OnCompleted(continuation);
  311. }
  312. else
  313. {
  314. continuation();
  315. }
  316. }
  317. }
  318. }
  319. }