72
|
1 using System.Threading;
|
75
|
2 using System;
|
|
3 #if NET_4_5
|
|
4 using System.Threading.Tasks;
|
|
5 #endif
|
72
|
6
|
|
7 namespace Implab {
|
|
8 public static class PromiseExtensions {
|
|
9 public static IPromise<T> DispatchToCurrentContext<T>(this IPromise<T> that) {
|
75
|
10 Safe.ArgumentNotNull(that, "that");
|
72
|
11 var context = SynchronizationContext.Current;
|
|
12 if (context == null)
|
|
13 return that;
|
|
14
|
|
15 var p = new SyncContextPromise<T>(context, that, true);
|
|
16
|
|
17 that.Then(
|
|
18 x => p.Resolve(x),
|
|
19 e => {
|
|
20 p.Reject(e);
|
|
21 return default(T);
|
|
22 }
|
|
23 );
|
|
24 return p;
|
|
25 }
|
|
26
|
|
27 public static IPromise<T> DispatchToContext<T>(this IPromise<T> that, SynchronizationContext context) {
|
75
|
28 Safe.ArgumentNotNull(that, "that");
|
72
|
29 Safe.ArgumentNotNull(context, "context");
|
|
30
|
|
31 var p = new SyncContextPromise<T>(context, that, true);
|
|
32
|
|
33 that.Then(
|
|
34 x => p.Resolve(x),
|
|
35 e => {
|
|
36 p.Reject(e);
|
|
37 return default(T);
|
|
38 }
|
|
39 );
|
|
40 return p;
|
|
41 }
|
75
|
42
|
|
43 public static AsyncCallback AsyncCallback<T>(this Promise<T> that, Func<IAsyncResult,T> callback) {
|
|
44 Safe.ArgumentNotNull(that, "that");
|
|
45 Safe.ArgumentNotNull(callback, "callback");
|
|
46 return ar => {
|
|
47 try {
|
|
48 that.Resolve(callback(ar));
|
|
49 } catch (Exception err) {
|
|
50 that.Reject(err);
|
|
51 }
|
|
52 };
|
|
53 }
|
|
54
|
|
55 #if NET_4_5
|
|
56
|
|
57 public static Task<T> GetTask<T>(this IPromise<T> that) {
|
|
58 Safe.ArgumentNotNull(that, "that");
|
|
59 var tcs = new TaskCompletionSource<T>();
|
|
60
|
|
61 that.Last(tcs.SetResult, tcs.SetException, tcs.SetCanceled);
|
|
62
|
|
63 return tcs.Task;
|
|
64 }
|
|
65
|
|
66 #endif
|
72
|
67 }
|
|
68 }
|
|
69
|