TaskObservableExtensions.cs 20 KB

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