1
0

TaskObservableExtensions.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the Apache 2.0 License.
  3. // See the LICENSE file in the project root for more information.
  4. using System.Reactive.Concurrency;
  5. using System.Reactive.Linq;
  6. using System.Reactive.Linq.ObservableImpl;
  7. using System.Reactive.Subjects;
  8. using System.Threading;
  9. using System.Threading.Tasks;
  10. namespace System.Reactive.Threading.Tasks
  11. {
  12. /// <summary>
  13. /// Provides a set of static methods for converting tasks to observable sequences.
  14. /// </summary>
  15. public static class TaskObservableExtensions
  16. {
  17. /// <summary>
  18. /// Returns an observable sequence that signals when the task completes.
  19. /// </summary>
  20. /// <param name="task">Task to convert to an observable sequence.</param>
  21. /// <returns>An observable sequence that produces a unit value when the task completes, or propagates the exception produced by the task.</returns>
  22. /// <exception cref="ArgumentNullException"><paramref name="task"/> is <c>null</c>.</exception>
  23. /// <remarks>If the specified task object supports cancellation, consider using <see cref="Observable.FromAsync(Func{CancellationToken, Task})"/> instead.</remarks>
  24. public static IObservable<Unit> ToObservable(this Task task)
  25. {
  26. if (task == null)
  27. {
  28. throw new ArgumentNullException(nameof(task));
  29. }
  30. return ToObservableImpl(task, scheduler: null);
  31. }
  32. /// <summary>
  33. /// Returns an observable sequence that signals when the task completes.
  34. /// </summary>
  35. /// <param name="task">Task to convert to an observable sequence.</param>
  36. /// <param name="scheduler">Scheduler on which to notify observers about completion, cancellation or failure.</param>
  37. /// <returns>An observable sequence that produces a unit value when the task completes, or propagates the exception produced by the task.</returns>
  38. /// <exception cref="ArgumentNullException"><paramref name="task"/> is <c>null</c> or <paramref name="scheduler"/> is <c>null</c>.</exception>
  39. /// <remarks>If the specified task object supports cancellation, consider using <see cref="Observable.FromAsync(Func{CancellationToken, Task})"/> instead.</remarks>
  40. public static IObservable<Unit> ToObservable(this Task task, IScheduler scheduler)
  41. {
  42. if (task == null)
  43. {
  44. throw new ArgumentNullException(nameof(task));
  45. }
  46. if (scheduler == null)
  47. {
  48. throw new ArgumentNullException(nameof(scheduler));
  49. }
  50. return ToObservableImpl(task, scheduler);
  51. }
  52. private static IObservable<Unit> ToObservableImpl(Task task, IScheduler scheduler)
  53. {
  54. var res = default(IObservable<Unit>);
  55. if (task.IsCompleted)
  56. {
  57. scheduler = scheduler ?? ImmediateScheduler.Instance;
  58. switch (task.Status)
  59. {
  60. case TaskStatus.RanToCompletion:
  61. res = new Return<Unit>(Unit.Default, scheduler);
  62. break;
  63. case TaskStatus.Faulted:
  64. res = new Throw<Unit>(task.Exception.InnerException, scheduler);
  65. break;
  66. case TaskStatus.Canceled:
  67. res = new Throw<Unit>(new TaskCanceledException(task), scheduler);
  68. break;
  69. }
  70. }
  71. else
  72. {
  73. //
  74. // Separate method to avoid closure in synchronous completion case.
  75. //
  76. res = ToObservableSlow(task, scheduler);
  77. }
  78. return res;
  79. }
  80. private static IObservable<Unit> ToObservableSlow(Task task, IScheduler scheduler)
  81. {
  82. var subject = new AsyncSubject<Unit>();
  83. var options = GetTaskContinuationOptions(scheduler);
  84. task.ContinueWith(t => ToObservableDone(task, subject), options);
  85. return ToObservableResult(subject, scheduler);
  86. }
  87. private static void ToObservableDone(Task task, IObserver<Unit> subject)
  88. {
  89. switch (task.Status)
  90. {
  91. case TaskStatus.RanToCompletion:
  92. subject.OnNext(Unit.Default);
  93. subject.OnCompleted();
  94. break;
  95. case TaskStatus.Faulted:
  96. subject.OnError(task.Exception.InnerException);
  97. break;
  98. case TaskStatus.Canceled:
  99. subject.OnError(new TaskCanceledException(task));
  100. break;
  101. }
  102. }
  103. /// <summary>
  104. /// Returns an observable sequence that propagates the result of the task.
  105. /// </summary>
  106. /// <typeparam name="TResult">The type of the result produced by the task.</typeparam>
  107. /// <param name="task">Task to convert to an observable sequence.</param>
  108. /// <returns>An observable sequence that produces the task's result, or propagates the exception produced by the task.</returns>
  109. /// <exception cref="ArgumentNullException"><paramref name="task"/> is <c>null</c>.</exception>
  110. /// <remarks>If the specified task object supports cancellation, consider using <see cref="Observable.FromAsync{TResult}(Func{CancellationToken, Task{TResult}})"/> instead.</remarks>
  111. public static IObservable<TResult> ToObservable<TResult>(this Task<TResult> task)
  112. {
  113. if (task == null)
  114. {
  115. throw new ArgumentNullException(nameof(task));
  116. }
  117. return ToObservableImpl(task, scheduler: null);
  118. }
  119. /// <summary>
  120. /// Returns an observable sequence that propagates the result of the task.
  121. /// </summary>
  122. /// <typeparam name="TResult">The type of the result produced by the task.</typeparam>
  123. /// <param name="task">Task to convert to an observable sequence.</param>
  124. /// <param name="scheduler">Scheduler on which to notify observers about completion, cancellation or failure.</param>
  125. /// <returns>An observable sequence that produces the task's result, or propagates the exception produced by the task.</returns>
  126. /// <exception cref="ArgumentNullException"><paramref name="task"/> is <c>null</c> or <paramref name="scheduler"/> is <c>null</c>.</exception>
  127. /// <remarks>If the specified task object supports cancellation, consider using <see cref="Observable.FromAsync{TResult}(Func{CancellationToken, Task{TResult}})"/> instead.</remarks>
  128. public static IObservable<TResult> ToObservable<TResult>(this Task<TResult> task, IScheduler scheduler)
  129. {
  130. if (task == null)
  131. {
  132. throw new ArgumentNullException(nameof(task));
  133. }
  134. if (scheduler == null)
  135. {
  136. throw new ArgumentNullException(nameof(scheduler));
  137. }
  138. return ToObservableImpl(task, scheduler);
  139. }
  140. private static IObservable<TResult> ToObservableImpl<TResult>(Task<TResult> task, IScheduler scheduler)
  141. {
  142. var res = default(IObservable<TResult>);
  143. if (task.IsCompleted)
  144. {
  145. scheduler = scheduler ?? ImmediateScheduler.Instance;
  146. switch (task.Status)
  147. {
  148. case TaskStatus.RanToCompletion:
  149. res = new Return<TResult>(task.Result, scheduler);
  150. break;
  151. case TaskStatus.Faulted:
  152. res = new Throw<TResult>(task.Exception.InnerException, scheduler);
  153. break;
  154. case TaskStatus.Canceled:
  155. res = new Throw<TResult>(new TaskCanceledException(task), scheduler);
  156. break;
  157. }
  158. }
  159. else
  160. {
  161. //
  162. // Separate method to avoid closure in synchronous completion case.
  163. //
  164. res = ToObservableSlow(task, scheduler);
  165. }
  166. return res;
  167. }
  168. private static IObservable<TResult> ToObservableSlow<TResult>(Task<TResult> task, IScheduler scheduler)
  169. {
  170. var subject = new AsyncSubject<TResult>();
  171. var options = GetTaskContinuationOptions(scheduler);
  172. task.ContinueWith(t => ToObservableDone(task, subject), options);
  173. return ToObservableResult(subject, scheduler);
  174. }
  175. private static void ToObservableDone<TResult>(Task<TResult> task, IObserver<TResult> subject)
  176. {
  177. switch (task.Status)
  178. {
  179. case TaskStatus.RanToCompletion:
  180. subject.OnNext(task.Result);
  181. subject.OnCompleted();
  182. break;
  183. case TaskStatus.Faulted:
  184. subject.OnError(task.Exception.InnerException);
  185. break;
  186. case TaskStatus.Canceled:
  187. subject.OnError(new TaskCanceledException(task));
  188. break;
  189. }
  190. }
  191. private static TaskContinuationOptions GetTaskContinuationOptions(IScheduler scheduler)
  192. {
  193. var options = TaskContinuationOptions.None;
  194. if (scheduler != null)
  195. {
  196. //
  197. // We explicitly don't special-case the immediate scheduler here. If the user asks for a
  198. // synchronous completion, we'll try our best. However, there's no guarantee due to the
  199. // internal stack probing in the TPL, which may cause asynchronous completion on a thread
  200. // pool thread in order to avoid stack overflows. Therefore we can only attempt to be more
  201. // efficient in the case where the user specified a scheduler, hence we know that the
  202. // continuation will trigger a scheduling operation. In case of the immediate scheduler,
  203. // it really becomes "immediate scheduling" wherever the TPL decided to run the continuation,
  204. // i.e. not necessarily where the task was completed from.
  205. //
  206. options |= TaskContinuationOptions.ExecuteSynchronously;
  207. }
  208. return options;
  209. }
  210. private static IObservable<TResult> ToObservableResult<TResult>(AsyncSubject<TResult> subject, IScheduler scheduler)
  211. {
  212. if (scheduler != null)
  213. {
  214. return subject.ObserveOn(scheduler);
  215. }
  216. return subject.AsObservable();
  217. }
  218. /// <summary>
  219. /// Returns a task that will receive the last value or the exception produced by the observable sequence.
  220. /// </summary>
  221. /// <typeparam name="TResult">The type of the elements in the source sequence.</typeparam>
  222. /// <param name="observable">Observable sequence to convert to a task.</param>
  223. /// <returns>A task that will receive the last element or the exception produced by the observable sequence.</returns>
  224. /// <exception cref="ArgumentNullException"><paramref name="observable"/> is <c>null</c>.</exception>
  225. public static Task<TResult> ToTask<TResult>(this IObservable<TResult> observable)
  226. {
  227. if (observable == null)
  228. {
  229. throw new ArgumentNullException(nameof(observable));
  230. }
  231. return observable.ToTask(new CancellationToken(), state: null);
  232. }
  233. /// <summary>
  234. /// Returns a task that will receive the last value or the exception produced by the observable sequence.
  235. /// </summary>
  236. /// <typeparam name="TResult">The type of the elements in the source sequence.</typeparam>
  237. /// <param name="observable">Observable sequence to convert to a task.</param>
  238. /// <param name="state">The state to use as the underlying task's AsyncState.</param>
  239. /// <returns>A task that will receive the last element or the exception produced by the observable sequence.</returns>
  240. /// <exception cref="ArgumentNullException"><paramref name="observable"/> is <c>null</c>.</exception>
  241. public static Task<TResult> ToTask<TResult>(this IObservable<TResult> observable, object state)
  242. {
  243. if (observable == null)
  244. {
  245. throw new ArgumentNullException(nameof(observable));
  246. }
  247. return observable.ToTask(new CancellationToken(), state);
  248. }
  249. /// <summary>
  250. /// Returns a task that will receive the last value or the exception produced by the observable sequence.
  251. /// </summary>
  252. /// <typeparam name="TResult">The type of the elements in the source sequence.</typeparam>
  253. /// <param name="observable">Observable sequence to convert to a task.</param>
  254. /// <param name="cancellationToken">Cancellation token that can be used to cancel the task, causing unsubscription from the observable sequence.</param>
  255. /// <returns>A task that will receive the last element or the exception produced by the observable sequence.</returns>
  256. /// <exception cref="ArgumentNullException"><paramref name="observable"/> is <c>null</c>.</exception>
  257. public static Task<TResult> ToTask<TResult>(this IObservable<TResult> observable, CancellationToken cancellationToken)
  258. {
  259. if (observable == null)
  260. {
  261. throw new ArgumentNullException(nameof(observable));
  262. }
  263. return observable.ToTask(cancellationToken, state: null);
  264. }
  265. private sealed class ToTaskObserver<TResult> : SafeObserver<TResult>
  266. {
  267. private readonly CancellationToken _ct;
  268. private readonly TaskCompletionSource<TResult> _tcs;
  269. private readonly CancellationTokenRegistration _ctr;
  270. private bool _hasValue;
  271. private TResult _lastValue;
  272. public ToTaskObserver(TaskCompletionSource<TResult> tcs, CancellationToken ct)
  273. {
  274. _ct = ct;
  275. _tcs = tcs;
  276. if (ct.CanBeCanceled)
  277. {
  278. _ctr = ct.Register(@this => ((ToTaskObserver<TResult>)@this).Cancel(), this);
  279. }
  280. }
  281. public override void OnNext(TResult value)
  282. {
  283. _hasValue = true;
  284. _lastValue = value;
  285. }
  286. public override void OnError(Exception error)
  287. {
  288. _tcs.TrySetException(error);
  289. _ctr.Dispose(); // no null-check needed (struct)
  290. Dispose();
  291. }
  292. public override void OnCompleted()
  293. {
  294. if (_hasValue)
  295. {
  296. _tcs.TrySetResult(_lastValue);
  297. }
  298. else
  299. {
  300. _tcs.TrySetException(new InvalidOperationException(Strings_Linq.NO_ELEMENTS));
  301. }
  302. _ctr.Dispose(); // no null-check needed (struct)
  303. Dispose();
  304. }
  305. private void Cancel()
  306. {
  307. Dispose();
  308. #if HAS_TPL46
  309. _tcs.TrySetCanceled(_ct);
  310. #else
  311. _tcs.TrySetCanceled();
  312. #endif
  313. }
  314. }
  315. /// <summary>
  316. /// Returns a task that will receive the last value or the exception produced by the observable sequence.
  317. /// </summary>
  318. /// <typeparam name="TResult">The type of the elements in the source sequence.</typeparam>
  319. /// <param name="observable">Observable sequence to convert to a task.</param>
  320. /// <param name="cancellationToken">Cancellation token that can be used to cancel the task, causing unsubscription from the observable sequence.</param>
  321. /// <param name="state">The state to use as the underlying task's <see cref="Task.AsyncState"/>.</param>
  322. /// <returns>A task that will receive the last element or the exception produced by the observable sequence.</returns>
  323. /// <exception cref="ArgumentNullException"><paramref name="observable"/> is <c>null</c>.</exception>
  324. public static Task<TResult> ToTask<TResult>(this IObservable<TResult> observable, CancellationToken cancellationToken, object state)
  325. {
  326. if (observable == null)
  327. {
  328. throw new ArgumentNullException(nameof(observable));
  329. }
  330. var tcs = new TaskCompletionSource<TResult>(state);
  331. var taskCompletionObserver = new ToTaskObserver<TResult>(tcs, cancellationToken);
  332. //
  333. // Subtle race condition: if the source completes before we reach the line below, the SingleAssigmentDisposable
  334. // will already have been disposed. Upon assignment, the disposable resource being set will be disposed on the
  335. // spot, which may throw an exception.
  336. //
  337. try
  338. {
  339. //
  340. // [OK] Use of unsafe Subscribe: we're catching the exception here to set the TaskCompletionSource.
  341. //
  342. // Notice we could use a safe subscription to route errors through OnError, but we still need the
  343. // exception handling logic here for the reason explained above. We cannot afford to throw here
  344. // and as a result never set the TaskCompletionSource, so we tunnel everything through here.
  345. //
  346. taskCompletionObserver.SetResource(observable.Subscribe/*Unsafe*/(taskCompletionObserver));
  347. }
  348. catch (Exception ex)
  349. {
  350. tcs.TrySetException(ex);
  351. }
  352. return tcs.Task;
  353. }
  354. }
  355. }