TaskObservableExtensions.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  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. switch (task.Status)
  28. {
  29. case TaskStatus.RanToCompletion:
  30. subject.OnNext(Unit.Default);
  31. subject.OnCompleted();
  32. break;
  33. case TaskStatus.Faulted:
  34. subject.OnError(task.Exception.InnerException);
  35. break;
  36. case TaskStatus.Canceled:
  37. subject.OnError(new TaskCanceledException(task));
  38. break;
  39. default:
  40. task.ContinueWith(t =>
  41. {
  42. switch (t.Status)
  43. {
  44. case TaskStatus.RanToCompletion:
  45. subject.OnNext(Unit.Default);
  46. subject.OnCompleted();
  47. break;
  48. case TaskStatus.Faulted:
  49. subject.OnError(t.Exception.InnerException);
  50. break;
  51. case TaskStatus.Canceled:
  52. subject.OnError(new TaskCanceledException(t));
  53. break;
  54. }
  55. });
  56. break;
  57. }
  58. return subject.AsObservable();
  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. switch (task.Status)
  74. {
  75. case TaskStatus.RanToCompletion:
  76. subject.OnNext(task.Result);
  77. subject.OnCompleted();
  78. break;
  79. case TaskStatus.Faulted:
  80. subject.OnError(task.Exception.InnerException);
  81. break;
  82. case TaskStatus.Canceled:
  83. subject.OnError(new TaskCanceledException(task));
  84. break;
  85. default:
  86. task.ContinueWith(t =>
  87. {
  88. switch (t.Status)
  89. {
  90. case TaskStatus.RanToCompletion:
  91. subject.OnNext(t.Result);
  92. subject.OnCompleted();
  93. break;
  94. case TaskStatus.Faulted:
  95. subject.OnError(t.Exception.InnerException);
  96. break;
  97. case TaskStatus.Canceled:
  98. subject.OnError(new TaskCanceledException(t));
  99. break;
  100. }
  101. });
  102. break;
  103. }
  104. return subject.AsObservable();
  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. cancellationToken.Register(() =>
  165. {
  166. disposable.Dispose();
  167. tcs.TrySetCanceled();
  168. });
  169. var taskCompletionObserver = new AnonymousObserver<TResult>(
  170. value =>
  171. {
  172. hasValue = true;
  173. lastValue = value;
  174. },
  175. ex =>
  176. {
  177. tcs.TrySetException(ex);
  178. disposable.Dispose();
  179. },
  180. () =>
  181. {
  182. if (hasValue)
  183. tcs.TrySetResult(lastValue);
  184. else
  185. tcs.TrySetException(new InvalidOperationException(Strings_Linq.NO_ELEMENTS));
  186. disposable.Dispose();
  187. }
  188. );
  189. //
  190. // Subtle race condition: if the source completes before we reach the line below, the SingleAssigmentDisposable
  191. // will already have been disposed. Upon assignment, the disposable resource being set will be disposed on the
  192. // spot, which may throw an exception. (Similar to TFS 487142)
  193. //
  194. try
  195. {
  196. //
  197. // [OK] Use of unsafe Subscribe: we're catching the exception here to set the TaskCompletionSource.
  198. //
  199. // Notice we could use a safe subscription to route errors through OnError, but we still need the
  200. // exception handling logic here for the reason explained above. We cannot afford to throw here
  201. // and as a result never set the TaskCompletionSource, so we tunnel everything through here.
  202. //
  203. disposable.Disposable = observable.Subscribe/*Unsafe*/(taskCompletionObserver);
  204. }
  205. catch (Exception ex)
  206. {
  207. tcs.TrySetException(ex);
  208. }
  209. return tcs.Task;
  210. }
  211. }
  212. }
  213. #endif