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