-
Notifications
You must be signed in to change notification settings - Fork 711
/
Copy pathRunOnUIThread.cs
116 lines (105 loc) · 3.84 KB
/
RunOnUIThread.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using System;
using System.Threading;
using System.Threading.Tasks;
using Windows.ApplicationModel.Core;
using Windows.UI.Core;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Media;
using Common;
#if USING_TAEF
using WEX.TestExecution;
using WEX.TestExecution.Markup;
using WEX.Logging.Interop;
#else
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.VisualStudio.TestTools.UnitTesting.Logging;
#endif
namespace MUXControlsTestApp.Utilities
{
public class RunOnUIThread
{
public static void Execute(Action action)
{
Execute(CoreApplication.MainView, action);
}
public static void Execute(CoreApplicationView whichView, Action action)
{
Exception exception = null;
var dispatcher = whichView.Dispatcher;
if (dispatcher.HasThreadAccess)
{
action();
}
else
{
// We're not on the UI thread, queue the work. Make sure that the action is not run until
// the splash screen is dismissed (i.e. that the window content is present).
var workComplete = new AutoResetEvent(false);
App.RunAfterSplashScreenDismissed(() =>
{
// If the Splash screen dismissal happens on the UI thread, run the action right now.
if (dispatcher.HasThreadAccess)
{
try
{
action();
}
catch (Exception e)
{
exception = e;
throw;
}
finally // Unblock calling thread even if action() throws
{
workComplete.Set();
}
}
else
{
// Otherwise queue the work to the UI thread and then set the completion event on that thread.
var ignore = dispatcher.RunAsync(CoreDispatcherPriority.Normal,
() => {
try
{
action();
}
catch (Exception e)
{
exception = e;
throw;
}
finally // Unblock calling thread even if action() throws
{
workComplete.Set();
}
});
}
});
workComplete.WaitOne();
if (exception != null)
{
Verify.Fail("Exception thrown by action on the UI thread: " + exception.ToString());
}
}
}
public static void WaitForTick()
{
var renderingEvent = new ManualResetEvent(false);
EventHandler<object> renderingHandler = (object sender, object args) =>
{
renderingEvent.Set();
};
RunOnUIThread.Execute(() =>
{
Windows.UI.Xaml.Media.CompositionTarget.Rendering += renderingHandler;
});
renderingEvent.WaitOne();
RunOnUIThread.Execute(() =>
{
Windows.UI.Xaml.Media.CompositionTarget.Rendering -= renderingHandler;
});
}
}
}