-
Notifications
You must be signed in to change notification settings - Fork 3
/
DispatcherTaskExtensions.cs
68 lines (64 loc) · 2.22 KB
/
DispatcherTaskExtensions.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.UI.Core;
namespace SDKTemplate
{
/// <summary>
/// Helper class used to run functions on the UI thread
/// </summary>
public static class DispatcherService
{
/// <summary>
/// Helper function to run task on UI thread
/// </summary>
/// <typeparam name="T">return value of task</typeparam>
/// <param name="dispatcher"></param>
/// <param name="func"></param>
/// <param name="priority"></param>
/// <returns>UI thread task</returns>
public 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.
/// <summary>
/// Helper function to run task on UI thread
/// </summary>
/// <param name="dispatcher"></param>
/// <param name="func"></param>
/// <param name="priority"></param>
/// <returns>UI thread task</returns>
public static async Task RunTaskAsync(
this CoreDispatcher dispatcher,
Func<Task> func,
CoreDispatcherPriority priority = CoreDispatcherPriority.Normal) =>
await RunTaskAsync(
dispatcher,
async () =>
{
await func();
return false;
},
priority);
}
}