TaskObservableExtensions.cs 18 KB

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