diff 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
line wrap: on
line diff
--- a/Implab/PromiseExtensions.cs	Mon Sep 08 17:40:46 2014 +0400
+++ b/Implab/PromiseExtensions.cs	Wed Sep 10 11:17:37 2014 +0400
@@ -1,8 +1,13 @@
 using System.Threading;
+using System;
+#if NET_4_5
+using System.Threading.Tasks;
+#endif
 
 namespace Implab {
     public static class PromiseExtensions {
         public static IPromise<T> DispatchToCurrentContext<T>(this IPromise<T> that) {
+            Safe.ArgumentNotNull(that, "that");
             var context = SynchronizationContext.Current;
             if (context == null)
                 return that;
@@ -20,6 +25,7 @@
         }
 
         public static IPromise<T> DispatchToContext<T>(this IPromise<T> that, SynchronizationContext context) {
+            Safe.ArgumentNotNull(that, "that");
             Safe.ArgumentNotNull(context, "context");
 
             var p = new SyncContextPromise<T>(context, that, true);
@@ -33,6 +39,31 @@
             );
             return p;
         }
+
+        public static AsyncCallback AsyncCallback<T>(this Promise<T> that, Func<IAsyncResult,T> callback) {
+            Safe.ArgumentNotNull(that, "that");
+            Safe.ArgumentNotNull(callback, "callback");
+            return ar => {
+                try {
+                    that.Resolve(callback(ar));
+                } catch (Exception err) {
+                    that.Reject(err);
+                }
+            };
+        }
+            
+        #if NET_4_5
+
+        public static Task<T> GetTask<T>(this IPromise<T> that) {
+            Safe.ArgumentNotNull(that, "that");
+            var tcs = new TaskCompletionSource<T>();
+
+            that.Last(tcs.SetResult, tcs.SetException, tcs.SetCanceled);
+
+            return tcs.Task;
+        }
+
+        #endif
     }
 }