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
|
101
|
15 var p = new SyncContextPromise<T>(context, that);
|
72
|
16
|
104
|
17 that.On(
|
76
|
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
|
101
|
29 var p = new SyncContextPromise<T>(context, that);
|
72
|
30
|
104
|
31 that.On(
|
76
|
32 p.Resolve,
|
|
33 p.Reject,
|
|
34 p.Cancel
|
72
|
35 );
|
|
36 return p;
|
|
37 }
|
75
|
38
|
101
|
39 /// <summary>
|
|
40 /// Ensures the dispatched.
|
|
41 /// </summary>
|
|
42 /// <returns>The dispatched.</returns>
|
|
43 /// <param name="that">That.</param>
|
|
44 /// <param name="head">Head.</param>
|
|
45 /// <param name="cleanup">Cleanup.</param>
|
|
46 /// <typeparam name="TPromise">The 1st type parameter.</typeparam>
|
|
47 /// <typeparam name="T">The 2nd type parameter.</typeparam>
|
|
48 public static TPromise EnsureDispatched<TPromise,T>(this TPromise that, IPromise<T> head, Action<T> cleanup) where TPromise : IPromise{
|
|
49 Safe.ArgumentNotNull(that, "that");
|
|
50 Safe.ArgumentNotNull(head, "head");
|
|
51
|
104
|
52 that.On(null,null,() => head.On(cleanup));
|
101
|
53
|
|
54 return that;
|
|
55 }
|
|
56
|
75
|
57 public static AsyncCallback AsyncCallback<T>(this Promise<T> that, Func<IAsyncResult,T> callback) {
|
|
58 Safe.ArgumentNotNull(that, "that");
|
|
59 Safe.ArgumentNotNull(callback, "callback");
|
|
60 return ar => {
|
|
61 try {
|
|
62 that.Resolve(callback(ar));
|
|
63 } catch (Exception err) {
|
|
64 that.Reject(err);
|
|
65 }
|
|
66 };
|
|
67 }
|
|
68
|
|
69 #if NET_4_5
|
|
70
|
|
71 public static Task<T> GetTask<T>(this IPromise<T> that) {
|
|
72 Safe.ArgumentNotNull(that, "that");
|
|
73 var tcs = new TaskCompletionSource<T>();
|
|
74
|
104
|
75 that.On(tcs.SetResult, tcs.SetException, tcs.SetCanceled);
|
75
|
76
|
|
77 return tcs.Task;
|
|
78 }
|
|
79
|
|
80 #endif
|
72
|
81 }
|
|
82 }
|
|
83
|