using System.Threading; using System; #if NET_4_5 using System.Threading.Tasks; #endif namespace Implab { public static class PromiseExtensions { public static IPromise DispatchToCurrentContext(this IPromise that) { Safe.ArgumentNotNull(that, "that"); var context = SynchronizationContext.Current; if (context == null) return that; var p = new SyncContextPromise(context, that); that.On( p.Resolve, p.Reject, p.Cancel ); return p; } public static IPromise DispatchToContext(this IPromise that, SynchronizationContext context) { Safe.ArgumentNotNull(that, "that"); Safe.ArgumentNotNull(context, "context"); var p = new SyncContextPromise(context, that); that.On( p.Resolve, p.Reject, p.Cancel ); return p; } /// /// Ensures the dispatched. /// /// The dispatched. /// That. /// Head. /// Cleanup. /// The 1st type parameter. /// The 2nd type parameter. public static TPromise EnsureDispatched(this TPromise that, IPromise head, Action cleanup) where TPromise : IPromise{ Safe.ArgumentNotNull(that, "that"); Safe.ArgumentNotNull(head, "head"); that.On(null,null,() => head.On(cleanup)); return that; } public static AsyncCallback AsyncCallback(this Promise that, Func 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 GetTask(this IPromise that) { Safe.ArgumentNotNull(that, "that"); var tcs = new TaskCompletionSource(); that.On(tcs.SetResult, tcs.SetException, tcs.SetCanceled); return tcs.Task; } #endif } }