diff --git a/ShortDev.Uwp.FullTrust/Windows/UI/Core/CoreDispatcherExtensions.cs b/ShortDev.Uwp.FullTrust/Windows/UI/Core/CoreDispatcherExtensions.cs new file mode 100644 index 0000000..93d316b --- /dev/null +++ b/ShortDev.Uwp.FullTrust/Windows/UI/Core/CoreDispatcherExtensions.cs @@ -0,0 +1,49 @@ +using System; +using System.Threading.Tasks; + +namespace Windows.UI.Core +{ + public static class CoreDispatcherExtensions + { + // https://github.com/Microsoft/Windows-task-snippets/blob/master/tasks/UI-thread-task-await-from-background-thread.md + + public static async Task RunTaskAsync(this CoreDispatcher @this, Func> callback, CoreDispatcherPriority priority = CoreDispatcherPriority.Normal) + { + TaskCompletionSource taskCompletionSource = new(); + _ = @this.RunAsync(priority, async () => + { + try + { + taskCompletionSource.SetResult(await callback()); + } + catch (Exception ex) + { + taskCompletionSource.SetException(ex); + } + }); + return await taskCompletionSource.Task; + } + + public static async Task RunTaskAsync(this CoreDispatcher @this, Func callback, CoreDispatcherPriority priority = CoreDispatcherPriority.Normal) + => await RunTaskAsync( + @this, + async () => + { + await callback(); + return true; + }, + priority + ); + + public static async Task RunTaskAsync(this CoreDispatcher @this, Action callback, CoreDispatcherPriority priority = CoreDispatcherPriority.Normal) + => await RunTaskAsync( + @this, + () => + { + callback(); + return Task.FromResult(true); + }, + priority + ); + } +}