TaskObservableExtensions.cs 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560
  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.Linq;
  7. using System.Reactive.Linq.ObservableImpl;
  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. private sealed class SlowTaskObservable : IObservable<Unit>
  18. {
  19. private readonly Task _task;
  20. private readonly IScheduler? _scheduler;
  21. public SlowTaskObservable(Task task, IScheduler? scheduler)
  22. {
  23. _task = task;
  24. _scheduler = scheduler;
  25. }
  26. public IDisposable Subscribe(IObserver<Unit> observer)
  27. {
  28. if (observer == null)
  29. {
  30. throw new ArgumentNullException(nameof(observer));
  31. }
  32. var cts = new CancellationDisposable();
  33. var options = GetTaskContinuationOptions(_scheduler);
  34. if (_scheduler == null)
  35. {
  36. _task.ContinueWith(static (t, subjectObject) => t.EmitTaskResult((IObserver<Unit>)subjectObject!), observer, cts.Token, options, TaskScheduler.Current);
  37. }
  38. else
  39. {
  40. _task.ContinueWithState(
  41. static (task, tuple) => tuple.@this._scheduler.ScheduleAction(
  42. (task, tuple.observer),
  43. static tuple2 => tuple2.task.EmitTaskResult(tuple2.observer)),
  44. (@this: this, observer),
  45. cts.Token,
  46. options);
  47. }
  48. return cts;
  49. }
  50. }
  51. private sealed class SlowTaskObservable<TResult> : IObservable<TResult>
  52. {
  53. private readonly Task<TResult> _task;
  54. private readonly IScheduler? _scheduler;
  55. public SlowTaskObservable(Task<TResult> task, IScheduler? scheduler)
  56. {
  57. _task = task;
  58. _scheduler = scheduler;
  59. }
  60. public IDisposable Subscribe(IObserver<TResult> observer)
  61. {
  62. if (observer == null)
  63. {
  64. throw new ArgumentNullException(nameof(observer));
  65. }
  66. var cts = new CancellationDisposable();
  67. var options = GetTaskContinuationOptions(_scheduler);
  68. if (_scheduler == null)
  69. {
  70. _task.ContinueWith(static (t, subjectObject) => t.EmitTaskResult((IObserver<TResult>)subjectObject!), observer, cts.Token, options, TaskScheduler.Current);
  71. }
  72. else
  73. {
  74. _task.ContinueWithState(
  75. static (task, tuple) => tuple.@this._scheduler.ScheduleAction(
  76. (task, tuple.observer),
  77. static tuple2 => tuple2.task.EmitTaskResult(tuple2.observer)),
  78. (@this: this, observer),
  79. cts.Token,
  80. options);
  81. }
  82. return cts;
  83. }
  84. }
  85. /// <summary>
  86. /// Returns an observable sequence that signals when the task completes.
  87. /// </summary>
  88. /// <param name="task">Task to convert to an observable sequence.</param>
  89. /// <returns>An observable sequence that produces a unit value when the task completes, or propagates the exception produced by the task.</returns>
  90. /// <exception cref="ArgumentNullException"><paramref name="task"/> is <c>null</c>.</exception>
  91. /// <remarks>If the specified task object supports cancellation, consider using <see cref="Observable.FromAsync(Func{CancellationToken, Task})"/> instead.</remarks>
  92. public static IObservable<Unit> ToObservable(this Task task)
  93. {
  94. if (task == null)
  95. {
  96. throw new ArgumentNullException(nameof(task));
  97. }
  98. return ToObservableImpl(task, scheduler: null);
  99. }
  100. /// <summary>
  101. /// Returns an observable sequence that signals when the task completes.
  102. /// </summary>
  103. /// <param name="task">Task to convert to an observable sequence.</param>
  104. /// <param name="scheduler">Scheduler on which to notify observers about completion, cancellation or failure.</param>
  105. /// <returns>An observable sequence that produces a unit value when the task completes, or propagates the exception produced by the task.</returns>
  106. /// <exception cref="ArgumentNullException"><paramref name="task"/> is <c>null</c> or <paramref name="scheduler"/> is <c>null</c>.</exception>
  107. /// <remarks>If the specified task object supports cancellation, consider using <see cref="Observable.FromAsync(Func{CancellationToken, Task})"/> instead.</remarks>
  108. public static IObservable<Unit> ToObservable(this Task task, IScheduler scheduler)
  109. {
  110. if (task == null)
  111. {
  112. throw new ArgumentNullException(nameof(task));
  113. }
  114. if (scheduler == null)
  115. {
  116. throw new ArgumentNullException(nameof(scheduler));
  117. }
  118. return ToObservableImpl(task, scheduler);
  119. }
  120. private static IObservable<Unit> ToObservableImpl(Task task, IScheduler? scheduler)
  121. {
  122. if (task.IsCompleted)
  123. {
  124. scheduler ??= ImmediateScheduler.Instance;
  125. return task.Status switch
  126. {
  127. TaskStatus.Faulted => new Throw<Unit>(task.GetSingleException(), scheduler),
  128. TaskStatus.Canceled => new Throw<Unit>(new TaskCanceledException(task), scheduler),
  129. _ => new Return<Unit>(Unit.Default, scheduler)
  130. };
  131. }
  132. return new SlowTaskObservable(task, scheduler);
  133. }
  134. private static void EmitTaskResult(this Task task, IObserver<Unit> subject)
  135. {
  136. switch (task.Status)
  137. {
  138. case TaskStatus.RanToCompletion:
  139. subject.OnNext(Unit.Default);
  140. subject.OnCompleted();
  141. break;
  142. case TaskStatus.Faulted:
  143. subject.OnError(task.GetSingleException());
  144. break;
  145. case TaskStatus.Canceled:
  146. subject.OnError(new TaskCanceledException(task));
  147. break;
  148. }
  149. }
  150. internal static IDisposable Subscribe(this Task task, IObserver<Unit> observer)
  151. {
  152. if (task.IsCompleted)
  153. {
  154. task.EmitTaskResult(observer);
  155. return Disposable.Empty;
  156. }
  157. var cts = new CancellationDisposable();
  158. task.ContinueWith(
  159. static (t, observerObject) => t.EmitTaskResult((IObserver<Unit>)observerObject!),
  160. observer,
  161. cts.Token,
  162. TaskContinuationOptions.ExecuteSynchronously,
  163. TaskScheduler.Current);
  164. return cts;
  165. }
  166. /// <summary>
  167. /// Returns an observable sequence that propagates the result of the task.
  168. /// </summary>
  169. /// <typeparam name="TResult">The type of the result produced by the task.</typeparam>
  170. /// <param name="task">Task to convert to an observable sequence.</param>
  171. /// <returns>An observable sequence that produces the task's result, or propagates the exception produced by the task.</returns>
  172. /// <exception cref="ArgumentNullException"><paramref name="task"/> is <c>null</c>.</exception>
  173. /// <remarks>If the specified task object supports cancellation, consider using <see cref="Observable.FromAsync{TResult}(Func{CancellationToken, Task{TResult}})"/> instead.</remarks>
  174. public static IObservable<TResult> ToObservable<TResult>(this Task<TResult> task)
  175. {
  176. if (task == null)
  177. {
  178. throw new ArgumentNullException(nameof(task));
  179. }
  180. return ToObservableImpl(task, scheduler: null);
  181. }
  182. /// <summary>
  183. /// Returns an observable sequence that propagates the result of the task.
  184. /// </summary>
  185. /// <typeparam name="TResult">The type of the result produced by the task.</typeparam>
  186. /// <param name="task">Task to convert to an observable sequence.</param>
  187. /// <param name="scheduler">Scheduler on which to notify observers about completion, cancellation or failure.</param>
  188. /// <returns>An observable sequence that produces the task's result, or propagates the exception produced by the task.</returns>
  189. /// <exception cref="ArgumentNullException"><paramref name="task"/> is <c>null</c> or <paramref name="scheduler"/> is <c>null</c>.</exception>
  190. /// <remarks>If the specified task object supports cancellation, consider using <see cref="Observable.FromAsync{TResult}(Func{CancellationToken, Task{TResult}})"/> instead.</remarks>
  191. public static IObservable<TResult> ToObservable<TResult>(this Task<TResult> task, IScheduler scheduler)
  192. {
  193. if (task == null)
  194. {
  195. throw new ArgumentNullException(nameof(task));
  196. }
  197. if (scheduler == null)
  198. {
  199. throw new ArgumentNullException(nameof(scheduler));
  200. }
  201. return ToObservableImpl(task, scheduler);
  202. }
  203. private static IObservable<TResult> ToObservableImpl<TResult>(Task<TResult> task, IScheduler? scheduler)
  204. {
  205. if (task.IsCompleted)
  206. {
  207. scheduler ??= ImmediateScheduler.Instance;
  208. return task.Status switch
  209. {
  210. TaskStatus.Faulted => new Throw<TResult>(task.GetSingleException(), scheduler),
  211. TaskStatus.Canceled => new Throw<TResult>(new TaskCanceledException(task), scheduler),
  212. _ => new Return<TResult>(task.Result, scheduler)
  213. };
  214. }
  215. return new SlowTaskObservable<TResult>(task, scheduler);
  216. }
  217. private static void EmitTaskResult<TResult>(this Task<TResult> task, IObserver<TResult> subject)
  218. {
  219. switch (task.Status)
  220. {
  221. case TaskStatus.RanToCompletion:
  222. subject.OnNext(task.Result);
  223. subject.OnCompleted();
  224. break;
  225. case TaskStatus.Faulted:
  226. subject.OnError(task.GetSingleException());
  227. break;
  228. case TaskStatus.Canceled:
  229. subject.OnError(new TaskCanceledException(task));
  230. break;
  231. }
  232. }
  233. private static TaskContinuationOptions GetTaskContinuationOptions(IScheduler? scheduler)
  234. {
  235. var options = TaskContinuationOptions.None;
  236. if (scheduler != null)
  237. {
  238. //
  239. // We explicitly don't special-case the immediate scheduler here. If the user asks for a
  240. // synchronous completion, we'll try our best. However, there's no guarantee due to the
  241. // internal stack probing in the TPL, which may cause asynchronous completion on a thread
  242. // pool thread in order to avoid stack overflows. Therefore we can only attempt to be more
  243. // efficient in the case where the user specified a scheduler, hence we know that the
  244. // continuation will trigger a scheduling operation. In case of the immediate scheduler,
  245. // it really becomes "immediate scheduling" wherever the TPL decided to run the continuation,
  246. // i.e. not necessarily where the task was completed from.
  247. //
  248. options |= TaskContinuationOptions.ExecuteSynchronously;
  249. }
  250. return options;
  251. }
  252. internal static IDisposable Subscribe<TResult>(this Task<TResult> task, IObserver<TResult> observer)
  253. {
  254. if (task.IsCompleted)
  255. {
  256. task.EmitTaskResult(observer);
  257. return Disposable.Empty;
  258. }
  259. var cts = new CancellationDisposable();
  260. task.ContinueWith(
  261. static (t, observerObject) => t.EmitTaskResult((IObserver<TResult>)observerObject!),
  262. observer,
  263. cts.Token,
  264. TaskContinuationOptions.ExecuteSynchronously,
  265. TaskScheduler.Current);
  266. return cts;
  267. }
  268. /// <summary>
  269. /// Returns a task that will receive the last value or the exception produced by the observable sequence.
  270. /// </summary>
  271. /// <typeparam name="TResult">The type of the elements in the source sequence.</typeparam>
  272. /// <param name="observable">Observable sequence to convert to a task.</param>
  273. /// <returns>A task that will receive the last element or the exception produced by the observable sequence.</returns>
  274. /// <exception cref="ArgumentNullException"><paramref name="observable"/> is <c>null</c>.</exception>
  275. public static Task<TResult> ToTask<TResult>(this IObservable<TResult> observable)
  276. {
  277. if (observable == null)
  278. {
  279. throw new ArgumentNullException(nameof(observable));
  280. }
  281. return observable.ToTask(new CancellationToken(), state: null);
  282. }
  283. /// <summary>
  284. /// Returns a task that will receive the last value or the exception produced by the observable sequence.
  285. /// </summary>
  286. /// <typeparam name="TResult">The type of the elements in the source sequence.</typeparam>
  287. /// <param name="observable">Observable sequence to convert to a task.</param>
  288. /// <param name="scheduler">The scheduler used for overriding where the task completion signals will be issued.</param>
  289. /// <returns>A task that will receive the last element or the exception produced by the observable sequence.</returns>
  290. /// <exception cref="ArgumentNullException"><paramref name="observable"/> or <paramref name="scheduler"/> is <c>null</c>.</exception>
  291. public static Task<TResult> ToTask<TResult>(this IObservable<TResult> observable, IScheduler scheduler)
  292. {
  293. return observable.ToTask().ContinueOnScheduler(scheduler);
  294. }
  295. /// <summary>
  296. /// Returns a task that will receive the last value or the exception produced by the observable sequence.
  297. /// </summary>
  298. /// <typeparam name="TResult">The type of the elements in the source sequence.</typeparam>
  299. /// <param name="observable">Observable sequence to convert to a task.</param>
  300. /// <param name="state">The state to use as the underlying task's AsyncState.</param>
  301. /// <returns>A task that will receive the last element or the exception produced by the observable sequence.</returns>
  302. /// <exception cref="ArgumentNullException"><paramref name="observable"/> is <c>null</c>.</exception>
  303. public static Task<TResult> ToTask<TResult>(this IObservable<TResult> observable, object? state)
  304. {
  305. if (observable == null)
  306. {
  307. throw new ArgumentNullException(nameof(observable));
  308. }
  309. return observable.ToTask(new CancellationToken(), state);
  310. }
  311. /// <summary>
  312. /// Returns a task that will receive the last value or the exception produced by the observable sequence.
  313. /// </summary>
  314. /// <typeparam name="TResult">The type of the elements in the source sequence.</typeparam>
  315. /// <param name="observable">Observable sequence to convert to a task.</param>
  316. /// <param name="state">The state to use as the underlying task's AsyncState.</param>
  317. /// <param name="scheduler">The scheduler used for overriding where the task completion signals will be issued.</param>
  318. /// <returns>A task that will receive the last element or the exception produced by the observable sequence.</returns>
  319. /// <exception cref="ArgumentNullException"><paramref name="observable"/> or <paramref name="scheduler"/> is <c>null</c>.</exception>
  320. public static Task<TResult> ToTask<TResult>(this IObservable<TResult> observable, object? state, IScheduler scheduler)
  321. {
  322. return observable.ToTask(new CancellationToken(), state).ContinueOnScheduler(scheduler);
  323. }
  324. /// <summary>
  325. /// Returns a task that will receive the last value or the exception produced by the observable sequence.
  326. /// </summary>
  327. /// <typeparam name="TResult">The type of the elements in the source sequence.</typeparam>
  328. /// <param name="observable">Observable sequence to convert to a task.</param>
  329. /// <param name="cancellationToken">Cancellation token that can be used to cancel the task, causing unsubscription from the observable sequence.</param>
  330. /// <returns>A task that will receive the last element or the exception produced by the observable sequence.</returns>
  331. /// <exception cref="ArgumentNullException"><paramref name="observable"/> is <c>null</c>.</exception>
  332. public static Task<TResult> ToTask<TResult>(this IObservable<TResult> observable, CancellationToken cancellationToken)
  333. {
  334. if (observable == null)
  335. {
  336. throw new ArgumentNullException(nameof(observable));
  337. }
  338. return observable.ToTask(cancellationToken, state: null);
  339. }
  340. /// <summary>
  341. /// Returns a task that will receive the last value or the exception produced by the observable sequence.
  342. /// </summary>
  343. /// <typeparam name="TResult">The type of the elements in the source sequence.</typeparam>
  344. /// <param name="observable">Observable sequence to convert to a task.</param>
  345. /// <param name="cancellationToken">Cancellation token that can be used to cancel the task, causing unsubscription from the observable sequence.</param>
  346. /// <param name="scheduler">The scheduler used for overriding where the task completion signals will be issued.</param>
  347. /// <returns>A task that will receive the last element or the exception produced by the observable sequence.</returns>
  348. /// <exception cref="ArgumentNullException"><paramref name="observable"/> or <paramref name="scheduler"/> is <c>null</c>.</exception>
  349. public static Task<TResult> ToTask<TResult>(this IObservable<TResult> observable, CancellationToken cancellationToken, IScheduler scheduler)
  350. {
  351. return observable.ToTask(cancellationToken, state: null).ContinueOnScheduler(scheduler);
  352. }
  353. internal static Task<TResult> ContinueOnScheduler<TResult>(this Task<TResult> task, IScheduler scheduler)
  354. {
  355. if (scheduler == null)
  356. {
  357. throw new ArgumentNullException(nameof(scheduler));
  358. }
  359. var tcs = new TaskCompletionSource<TResult>(task.AsyncState);
  360. task.ContinueWith(
  361. static (t, o) =>
  362. {
  363. var (scheduler, tcs) = ((IScheduler, TaskCompletionSource<TResult>))o!;
  364. scheduler.ScheduleAction((t, tcs), static state =>
  365. {
  366. if (state.t.IsCanceled)
  367. {
  368. state.tcs.TrySetCanceled(new TaskCanceledException(state.t).CancellationToken);
  369. }
  370. else if (state.t.IsFaulted)
  371. {
  372. state.tcs.TrySetException(state.t.GetSingleException());
  373. }
  374. else
  375. {
  376. state.tcs.TrySetResult(state.t.Result);
  377. }
  378. });
  379. },
  380. (scheduler, tcs),
  381. TaskContinuationOptions.ExecuteSynchronously);
  382. return tcs.Task;
  383. }
  384. private sealed class ToTaskObserver<TResult> : SafeObserver<TResult>
  385. {
  386. private readonly CancellationToken _ct;
  387. private readonly TaskCompletionSource<TResult> _tcs;
  388. private readonly CancellationTokenRegistration _ctr;
  389. private bool _hasValue;
  390. private TResult? _lastValue;
  391. public ToTaskObserver(TaskCompletionSource<TResult> tcs, CancellationToken ct)
  392. {
  393. _ct = ct;
  394. _tcs = tcs;
  395. if (ct.CanBeCanceled)
  396. {
  397. _ctr = ct.Register(static @this => ((ToTaskObserver<TResult>)@this!).Cancel(), this);
  398. }
  399. }
  400. public override void OnNext(TResult value)
  401. {
  402. _hasValue = true;
  403. _lastValue = value;
  404. }
  405. public override void OnError(Exception error)
  406. {
  407. _tcs.TrySetException(error);
  408. _ctr.Dispose(); // no null-check needed (struct)
  409. Dispose();
  410. }
  411. public override void OnCompleted()
  412. {
  413. if (_hasValue)
  414. {
  415. _tcs.TrySetResult(_lastValue!);
  416. }
  417. else
  418. {
  419. try
  420. {
  421. throw new InvalidOperationException(Strings_Linq.NO_ELEMENTS);
  422. }
  423. catch (Exception e)
  424. {
  425. _tcs.TrySetException(e);
  426. }
  427. }
  428. _ctr.Dispose(); // no null-check needed (struct)
  429. Dispose();
  430. }
  431. private void Cancel()
  432. {
  433. Dispose();
  434. _tcs.TrySetCanceled(_ct);
  435. }
  436. }
  437. /// <summary>
  438. /// Returns a task that will receive the last value or the exception produced by the observable sequence.
  439. /// </summary>
  440. /// <typeparam name="TResult">The type of the elements in the source sequence.</typeparam>
  441. /// <param name="observable">Observable sequence to convert to a task.</param>
  442. /// <param name="cancellationToken">Cancellation token that can be used to cancel the task, causing unsubscription from the observable sequence.</param>
  443. /// <param name="state">The state to use as the underlying task's <see cref="Task.AsyncState"/>.</param>
  444. /// <returns>A task that will receive the last element or the exception produced by the observable sequence.</returns>
  445. /// <exception cref="ArgumentNullException"><paramref name="observable"/> is <c>null</c>.</exception>
  446. public static Task<TResult> ToTask<TResult>(this IObservable<TResult> observable, CancellationToken cancellationToken, object? state)
  447. {
  448. if (observable == null)
  449. {
  450. throw new ArgumentNullException(nameof(observable));
  451. }
  452. var tcs = new TaskCompletionSource<TResult>(state);
  453. var taskCompletionObserver = new ToTaskObserver<TResult>(tcs, cancellationToken);
  454. //
  455. // Subtle race condition: if the source completes before we reach the line below, the SingleAssigmentDisposable
  456. // will already have been disposed. Upon assignment, the disposable resource being set will be disposed on the
  457. // spot, which may throw an exception.
  458. //
  459. try
  460. {
  461. //
  462. // [OK] Use of unsafe Subscribe: we're catching the exception here to set the TaskCompletionSource.
  463. //
  464. // Notice we could use a safe subscription to route errors through OnError, but we still need the
  465. // exception handling logic here for the reason explained above. We cannot afford to throw here
  466. // and as a result never set the TaskCompletionSource, so we tunnel everything through here.
  467. //
  468. taskCompletionObserver.SetResource(observable.Subscribe/*Unsafe*/(taskCompletionObserver));
  469. }
  470. catch (Exception ex)
  471. {
  472. tcs.TrySetException(ex);
  473. }
  474. return tcs.Task;
  475. }
  476. /// <summary>
  477. /// Returns a task that will receive the last value or the exception produced by the observable sequence.
  478. /// </summary>
  479. /// <typeparam name="TResult">The type of the elements in the source sequence.</typeparam>
  480. /// <param name="observable">Observable sequence to convert to a task.</param>
  481. /// <param name="cancellationToken">Cancellation token that can be used to cancel the task, causing unsubscription from the observable sequence.</param>
  482. /// <param name="state">The state to use as the underlying task's <see cref="Task.AsyncState"/>.</param>
  483. /// <param name="scheduler">The scheduler used for overriding where the task completion signals will be issued.</param>
  484. /// <returns>A task that will receive the last element or the exception produced by the observable sequence.</returns>
  485. /// <exception cref="ArgumentNullException"><paramref name="observable"/> or <paramref name="scheduler"/> is <c>null</c>.</exception>
  486. public static Task<TResult> ToTask<TResult>(this IObservable<TResult> observable, CancellationToken cancellationToken, object state, IScheduler scheduler)
  487. {
  488. return observable.ToTask(cancellationToken, state).ContinueOnScheduler(scheduler);
  489. }
  490. }
  491. }