Mercurial > pub > ImplabNet
comparison Implab/PromiseExtensions.cs @ 75:4439140706d0 v2
major refactoring, added tasks support
author | cin |
---|---|
date | Wed, 10 Sep 2014 11:17:37 +0400 |
parents | d67b95eddaf4 |
children | c761fc982e1d |
comparison
equal
deleted
inserted
replaced
74:c4140283575c | 75:4439140706d0 |
---|---|
1 using System.Threading; | 1 using System.Threading; |
2 using System; | |
3 #if NET_4_5 | |
4 using System.Threading.Tasks; | |
5 #endif | |
2 | 6 |
3 namespace Implab { | 7 namespace Implab { |
4 public static class PromiseExtensions { | 8 public static class PromiseExtensions { |
5 public static IPromise<T> DispatchToCurrentContext<T>(this IPromise<T> that) { | 9 public static IPromise<T> DispatchToCurrentContext<T>(this IPromise<T> that) { |
10 Safe.ArgumentNotNull(that, "that"); | |
6 var context = SynchronizationContext.Current; | 11 var context = SynchronizationContext.Current; |
7 if (context == null) | 12 if (context == null) |
8 return that; | 13 return that; |
9 | 14 |
10 var p = new SyncContextPromise<T>(context, that, true); | 15 var p = new SyncContextPromise<T>(context, that, true); |
18 ); | 23 ); |
19 return p; | 24 return p; |
20 } | 25 } |
21 | 26 |
22 public static IPromise<T> DispatchToContext<T>(this IPromise<T> that, SynchronizationContext context) { | 27 public static IPromise<T> DispatchToContext<T>(this IPromise<T> that, SynchronizationContext context) { |
28 Safe.ArgumentNotNull(that, "that"); | |
23 Safe.ArgumentNotNull(context, "context"); | 29 Safe.ArgumentNotNull(context, "context"); |
24 | 30 |
25 var p = new SyncContextPromise<T>(context, that, true); | 31 var p = new SyncContextPromise<T>(context, that, true); |
26 | 32 |
27 that.Then( | 33 that.Then( |
31 return default(T); | 37 return default(T); |
32 } | 38 } |
33 ); | 39 ); |
34 return p; | 40 return p; |
35 } | 41 } |
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 | |
36 } | 67 } |
37 } | 68 } |
38 | 69 |