namespace Monaco.Helpers
{
using System;
using System.Threading.Tasks;
using Windows.UI.Core;
///
/// https://github.com/Microsoft/Windows-task-snippets/blob/master/tasks/UI-thread-task-await-from-background-thread.md
///
internal static class DispatcherTaskExtensions
{
internal static async Task RunTaskAsync(this CoreDispatcher dispatcher,
Func> func, CoreDispatcherPriority priority = CoreDispatcherPriority.Normal)
{
var taskCompletionSource = new TaskCompletionSource();
await dispatcher.RunAsync(priority, async () =>
{
try
{
taskCompletionSource.SetResult(await func());
}
catch (Exception ex)
{
taskCompletionSource.SetException(ex);
}
});
return await taskCompletionSource.Task;
}
// There is no TaskCompletionSource so we use a bool that we throw away.
internal static async Task RunTaskAsync(this CoreDispatcher dispatcher,
Func func, CoreDispatcherPriority priority = CoreDispatcherPriority.Normal) =>
await RunTaskAsync(dispatcher, async () => { await func(); return false; }, priority);
}
}