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
|
76
|
17 that.Last(
|
|
18 p.Resolve,
|
|
19 p.Reject,
|
|
20 p.Cancel
|
72
|
21 );
|
|
22 return p;
|
|
23 }
|
|
24
|
|
25 public static IPromise<T> DispatchToContext<T>(this IPromise<T> that, SynchronizationContext context) {
|
75
|
26 Safe.ArgumentNotNull(that, "that");
|
72
|
27 Safe.ArgumentNotNull(context, "context");
|
|
28
|
|
29 var p = new SyncContextPromise<T>(context, that, true);
|
|
30
|
76
|
31 that.Last(
|
|
32 p.Resolve,
|
|
33 p.Reject,
|
|
34 p.Cancel
|
72
|
35 );
|
|
36 return p;
|
|
37 }
|
75
|
38
|
|
39 public static AsyncCallback AsyncCallback<T>(this Promise<T> that, Func<IAsyncResult,T> callback) {
|
|
40 Safe.ArgumentNotNull(that, "that");
|
|
41 Safe.ArgumentNotNull(callback, "callback");
|
|
42 return ar => {
|
|
43 try {
|
|
44 that.Resolve(callback(ar));
|
|
45 } catch (Exception err) {
|
|
46 that.Reject(err);
|
|
47 }
|
|
48 };
|
|
49 }
|
|
50
|
|
51 #if NET_4_5
|
|
52
|
|
53 public static Task<T> GetTask<T>(this IPromise<T> that) {
|
|
54 Safe.ArgumentNotNull(that, "that");
|
|
55 var tcs = new TaskCompletionSource<T>();
|
|
56
|
|
57 that.Last(tcs.SetResult, tcs.SetException, tcs.SetCanceled);
|
|
58
|
|
59 return tcs.Task;
|
|
60 }
|
|
61
|
|
62 #endif
|
72
|
63 }
|
|
64 }
|
|
65
|