TaskObservableExtensions.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  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. namespace System.Reactive.Threading.Tasks
  9. {
  10. /// <summary>
  11. /// Provides a set of static methods for converting tasks to observable sequences.
  12. /// </summary>
  13. public static class TaskObservableExtensions
  14. {
  15. /// <summary>
  16. /// Returns an observable sequence that signals when the task completes.
  17. /// </summary>
  18. /// <param name="task">Task to convert to an observable sequence.</param>
  19. /// <returns>An observable sequence that produces a unit value when the task completes, or propagates the exception produced by the task.</returns>
  20. /// <exception cref="ArgumentNullException"><paramref name="task"/> is null.</exception>
  21. /// <remarks>If the specified task object supports cancellation, consider using <see cref="Observable.FromAsync(Func{CancellationToken, Task})"/> instead.</remarks>
  22. public static IObservable<Unit> ToObservable(this Task task)
  23. {
  24. if (task == null)
  25. throw new ArgumentNullException("task");
  26. var subject = new AsyncSubject<Unit>();
  27. if (task.IsCompleted)
  28. {
  29. ToObservableDone(task, subject);
  30. }
  31. else
  32. {
  33. ToObservableSlow(task, subject);
  34. }
  35. return subject.AsObservable();
  36. }
  37. private static void ToObservableSlow(Task task, AsyncSubject<Unit> subject)
  38. {
  39. //
  40. // Separate method to avoid closure in synchronous completion case.
  41. //
  42. task.ContinueWith(t => ToObservableDone(task, subject));
  43. }
  44. private static void ToObservableDone(Task task, AsyncSubject<Unit> subject)
  45. {
  46. switch (task.Status)
  47. {
  48. case TaskStatus.RanToCompletion:
  49. subject.OnNext(Unit.Default);
  50. subject.OnCompleted();
  51. break;
  52. case TaskStatus.Faulted:
  53. subject.OnError(task.Exception.InnerException);
  54. break;
  55. case TaskStatus.Canceled:
  56. subject.OnError(new TaskCanceledException(task));
  57. break;
  58. }
  59. }
  60. /// <summary>
  61. /// Returns an observable sequence that propagates the result of the task.
  62. /// </summary>
  63. /// <typeparam name="TResult">The type of the result produced by the task.</typeparam>
  64. /// <param name="task">Task to convert to an observable sequence.</param>
  65. /// <returns>An observable sequence that produces the task's result, or propagates the exception produced by the task.</returns>
  66. /// <exception cref="ArgumentNullException"><paramref name="task"/> is null.</exception>
  67. /// <remarks>If the specified task object supports cancellation, consider using <see cref="Observable.FromAsync{TResult}(Func{CancellationToken, Task{TResult}})"/> instead.</remarks>
  68. public static IObservable<TResult> ToObservable<TResult>(this Task<TResult> task)
  69. {
  70. if (task == null)
  71. throw new ArgumentNullException("task");
  72. var subject = new AsyncSubject<TResult>();
  73. if (task.IsCompleted)
  74. {
  75. ToObservableDone<TResult>(task, subject);
  76. }
  77. else
  78. {
  79. ToObservableSlow<TResult>(task, subject);
  80. }
  81. return subject.AsObservable();
  82. }
  83. private static void ToObservableSlow<TResult>(Task<TResult> task, AsyncSubject<TResult> subject)
  84. {
  85. //
  86. // Separate method to avoid closure in synchronous completion case.
  87. //
  88. task.ContinueWith(t => ToObservableDone(t, subject));
  89. }
  90. private static void ToObservableDone<TResult>(Task<TResult> task, AsyncSubject<TResult> subject)
  91. {
  92. switch (task.Status)
  93. {
  94. case TaskStatus.RanToCompletion:
  95. subject.OnNext(task.Result);
  96. subject.OnCompleted();
  97. break;
  98. case TaskStatus.Faulted:
  99. subject.OnError(task.Exception.InnerException);
  100. break;
  101. case TaskStatus.Canceled:
  102. subject.OnError(new TaskCanceledException(task));
  103. break;
  104. }
  105. }
  106. /// <summary>
  107. /// Returns a task that will receive the last value or the exception produced by the observable sequence.
  108. /// </summary>
  109. /// <typeparam name="TResult">The type of the elements in the source sequence.</typeparam>
  110. /// <param name="observable">Observable sequence to convert to a task.</param>
  111. /// <returns>A task that will receive the last element or the exception produced by the observable sequence.</returns>
  112. /// <exception cref="ArgumentNullException"><paramref name="observable"/> is null.</exception>
  113. public static Task<TResult> ToTask<TResult>(this IObservable<TResult> observable)
  114. {
  115. if (observable == null)
  116. throw new ArgumentNullException("observable");
  117. return observable.ToTask(new CancellationToken(), null);
  118. }
  119. /// <summary>
  120. /// Returns a task that will receive the last value or the exception produced by the observable sequence.
  121. /// </summary>
  122. /// <typeparam name="TResult">The type of the elements in the source sequence.</typeparam>
  123. /// <param name="observable">Observable sequence to convert to a task.</param>
  124. /// <param name="state">The state to use as the underlying task's AsyncState.</param>
  125. /// <returns>A task that will receive the last element or the exception produced by the observable sequence.</returns>
  126. /// <exception cref="ArgumentNullException"><paramref name="observable"/> is null.</exception>
  127. public static Task<TResult> ToTask<TResult>(this IObservable<TResult> observable, object state)
  128. {
  129. if (observable == null)
  130. throw new ArgumentNullException("observable");
  131. return observable.ToTask(new CancellationToken(), state);
  132. }
  133. /// <summary>
  134. /// Returns a task that will receive the last value or the exception produced by the observable sequence.
  135. /// </summary>
  136. /// <typeparam name="TResult">The type of the elements in the source sequence.</typeparam>
  137. /// <param name="observable">Observable sequence to convert to a task.</param>
  138. /// <param name="cancellationToken">Cancellation token that can be used to cancel the task, causing unsubscription from the observable sequence.</param>
  139. /// <returns>A task that will receive the last element or the exception produced by the observable sequence.</returns>
  140. /// <exception cref="ArgumentNullException"><paramref name="observable"/> is null.</exception>
  141. public static Task<TResult> ToTask<TResult>(this IObservable<TResult> observable, CancellationToken cancellationToken)
  142. {
  143. if (observable == null)
  144. throw new ArgumentNullException("observable");
  145. return observable.ToTask(cancellationToken, null);
  146. }
  147. /// <summary>
  148. /// Returns a task that will receive the last value or the exception produced by the observable sequence.
  149. /// </summary>
  150. /// <typeparam name="TResult">The type of the elements in the source sequence.</typeparam>
  151. /// <param name="observable">Observable sequence to convert to a task.</param>
  152. /// <param name="cancellationToken">Cancellation token that can be used to cancel the task, causing unsubscription from the observable sequence.</param>
  153. /// <param name="state">The state to use as the underlying task's AsyncState.</param>
  154. /// <returns>A task that will receive the last element or the exception produced by the observable sequence.</returns>
  155. /// <exception cref="ArgumentNullException"><paramref name="observable"/> is null.</exception>
  156. public static Task<TResult> ToTask<TResult>(this IObservable<TResult> observable, CancellationToken cancellationToken, object state)
  157. {
  158. if (observable == null)
  159. throw new ArgumentNullException("observable");
  160. var hasValue = false;
  161. var lastValue = default(TResult);
  162. var tcs = new TaskCompletionSource<TResult>(state);
  163. var disposable = new SingleAssignmentDisposable();
  164. var ctr = default(CancellationTokenRegistration);
  165. if (cancellationToken.CanBeCanceled)
  166. {
  167. ctr = cancellationToken.Register(() =>
  168. {
  169. disposable.Dispose();
  170. tcs.TrySetCanceled(cancellationToken);
  171. });
  172. }
  173. var taskCompletionObserver = new AnonymousObserver<TResult>(
  174. value =>
  175. {
  176. hasValue = true;
  177. lastValue = value;
  178. },
  179. ex =>
  180. {
  181. tcs.TrySetException(ex);
  182. ctr.Dispose(); // no null-check needed (struct)
  183. disposable.Dispose();
  184. },
  185. () =>
  186. {
  187. if (hasValue)
  188. tcs.TrySetResult(lastValue);
  189. else
  190. tcs.TrySetException(new InvalidOperationException(Strings_Linq.NO_ELEMENTS));
  191. ctr.Dispose(); // no null-check needed (struct)
  192. disposable.Dispose();
  193. }
  194. );
  195. //
  196. // Subtle race condition: if the source completes before we reach the line below, the SingleAssigmentDisposable
  197. // will already have been disposed. Upon assignment, the disposable resource being set will be disposed on the
  198. // spot, which may throw an exception. (Similar to TFS 487142)
  199. //
  200. try
  201. {
  202. //
  203. // [OK] Use of unsafe Subscribe: we're catching the exception here to set the TaskCompletionSource.
  204. //
  205. // Notice we could use a safe subscription to route errors through OnError, but we still need the
  206. // exception handling logic here for the reason explained above. We cannot afford to throw here
  207. // and as a result never set the TaskCompletionSource, so we tunnel everything through here.
  208. //
  209. disposable.Disposable = observable.Subscribe/*Unsafe*/(taskCompletionObserver);
  210. }
  211. catch (Exception ex)
  212. {
  213. tcs.TrySetException(ex);
  214. }
  215. return tcs.Task;
  216. }
  217. }
  218. }
  219. #endif