You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
35 lines
1.3 KiB
35 lines
1.3 KiB
namespace Monaco.Helpers |
|
{ |
|
using System; |
|
using System.Threading.Tasks; |
|
using Windows.UI.Core; |
|
|
|
/// <summary> |
|
/// https://github.com/Microsoft/Windows-task-snippets/blob/master/tasks/UI-thread-task-await-from-background-thread.md |
|
/// </summary> |
|
internal static class DispatcherTaskExtensions |
|
{ |
|
internal static async Task<T> RunTaskAsync<T>(this CoreDispatcher dispatcher, |
|
Func<Task<T>> func, CoreDispatcherPriority priority = CoreDispatcherPriority.Normal) |
|
{ |
|
var taskCompletionSource = new TaskCompletionSource<T>(); |
|
await dispatcher.RunAsync(priority, async () => |
|
{ |
|
try |
|
{ |
|
taskCompletionSource.SetResult(await func()); |
|
} |
|
catch (Exception ex) |
|
{ |
|
taskCompletionSource.SetException(ex); |
|
} |
|
}); |
|
return await taskCompletionSource.Task; |
|
} |
|
|
|
// There is no TaskCompletionSource<void> so we use a bool that we throw away. |
|
internal static async Task RunTaskAsync(this CoreDispatcher dispatcher, |
|
Func<Task> func, CoreDispatcherPriority priority = CoreDispatcherPriority.Normal) => |
|
await RunTaskAsync(dispatcher, async () => { await func(); return false; }, priority); |
|
} |
|
}
|
|
|