PromiseExtensions.cs
83 lines
| 2.5 KiB
| text/x-csharp
|
CSharpLexer
/ Implab / PromiseExtensions.cs
|
|
r72 | using System.Threading; | ||
|
|
r75 | using System; | ||
| #if NET_4_5 | ||||
| using System.Threading.Tasks; | ||||
| #endif | ||||
|
|
r72 | |||
| namespace Implab { | ||||
| public static class PromiseExtensions { | ||||
| public static IPromise<T> DispatchToCurrentContext<T>(this IPromise<T> that) { | ||||
|
|
r75 | Safe.ArgumentNotNull(that, "that"); | ||
|
|
r72 | var context = SynchronizationContext.Current; | ||
| if (context == null) | ||||
| return that; | ||||
|
|
r101 | var p = new SyncContextPromise<T>(context, that); | ||
|
|
r72 | |||
|
|
r104 | that.On( | ||
|
|
r76 | p.Resolve, | ||
| p.Reject, | ||||
| p.Cancel | ||||
|
|
r72 | ); | ||
| return p; | ||||
| } | ||||
| public static IPromise<T> DispatchToContext<T>(this IPromise<T> that, SynchronizationContext context) { | ||||
|
|
r75 | Safe.ArgumentNotNull(that, "that"); | ||
|
|
r72 | Safe.ArgumentNotNull(context, "context"); | ||
|
|
r101 | var p = new SyncContextPromise<T>(context, that); | ||
|
|
r72 | |||
|
|
r104 | that.On( | ||
|
|
r76 | p.Resolve, | ||
| p.Reject, | ||||
| p.Cancel | ||||
|
|
r72 | ); | ||
| return p; | ||||
| } | ||||
|
|
r75 | |||
|
|
r101 | /// <summary> | ||
| /// Ensures the dispatched. | ||||
| /// </summary> | ||||
| /// <returns>The dispatched.</returns> | ||||
| /// <param name="that">That.</param> | ||||
| /// <param name="head">Head.</param> | ||||
| /// <param name="cleanup">Cleanup.</param> | ||||
| /// <typeparam name="TPromise">The 1st type parameter.</typeparam> | ||||
| /// <typeparam name="T">The 2nd type parameter.</typeparam> | ||||
| public static TPromise EnsureDispatched<TPromise,T>(this TPromise that, IPromise<T> head, Action<T> cleanup) where TPromise : IPromise{ | ||||
| Safe.ArgumentNotNull(that, "that"); | ||||
| Safe.ArgumentNotNull(head, "head"); | ||||
|
|
r104 | that.On(null,null,() => head.On(cleanup)); | ||
|
|
r101 | |||
| return that; | ||||
| } | ||||
|
|
r75 | 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>(); | ||||
|
|
r104 | that.On(tcs.SetResult, tcs.SetException, tcs.SetCanceled); | ||
|
|
r75 | |||
| return tcs.Task; | ||||
| } | ||||
| #endif | ||||
|
|
r72 | } | ||
| } | ||||
