1
0

TaskObservableExtensions.cs 17 KB

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