/// <summary> /// Executes the specified <paramref name="asyncFunc"/> on the specified <paramref name="synchronizationContext"/> and returns the result /// </summary> /// <typeparam name="TResult">The return type of <paramref name="asyncFunc"/></typeparam> /// <param name="synchronizationContext">The <see cref="SynchronizationContext"/></param> /// <param name="asyncFunc">The <see cref="Func{Task}"/> that returns a value</param> /// <returns>The result of <paramref name="asyncFunc"/></returns> public static async Task <TResult> ExecuteAsync <TResult>(this SynchronizationContext synchronizationContext, Func <Task <TResult> > asyncFunc) { if (synchronizationContext == null || SynchronizationContext.Current == synchronizationContext) { return(await asyncFunc().ConfigureAwait(false)); } var completion = new TaskCompletionSource <TResult>(); synchronizationContext.Post(async state => await completion.AttemptSetResultAsync(asyncFunc).ConfigureAwait(false), null); return(await completion.Task.ConfigureAwait(false)); }
/// <summary> /// Executes the specified <paramref name="asyncAction"/> on the specified <paramref name="synchronizationContext"/> /// </summary> /// <param name="synchronizationContext">The <see cref="SynchronizationContext"/></param> /// <param name="asyncAction">The <see cref="Func{Task}"/></param> public static async Task ExecuteAsync(this SynchronizationContext synchronizationContext, Func <Task> asyncAction) { if (synchronizationContext == null || SynchronizationContext.Current == synchronizationContext) { await asyncAction().ConfigureAwait(false); return; } var completion = new TaskCompletionSource <object>(); synchronizationContext.Post(async state => await completion.AttemptSetResultAsync(asyncAction).ConfigureAwait(false), null); await completion.Task.ConfigureAwait(false); }