Run code on UI thread in WinRT

2019-01-02 15:35发布

How can I run code on the UI thread in WinRT (Windows 8 Metro)?

The Invoke method does not exist.

6条回答
与君花间醉酒
2楼-- · 2019-01-02 15:37

Use:

this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => Frame.Navigate(typeof(Welcome), this));

It works for me.

查看更多
明月照影归
3楼-- · 2019-01-02 15:44

It's easier to directly get the CoreWindow from the non-UI thread. The following code will work everywhere, even when GetForCurrentThread() or Window.Current returns null.

CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
    <lambda for your code which should run on the UI thread>);

for example:

CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
    () =>
    {
        // Your UI update code goes here!
    });

You'll need to reference Windows.ApplicationModel.Core namespace:

using Windows.ApplicationModel.Core;
查看更多
倾城一夜雪
4楼-- · 2019-01-02 15:57

Use:

From your UI thread, execute:

var dispatcher = Windows.UI.Core.CoreWindow.GetForCurrentThread().Dispatcher;

From your background (non UI thread)

dispatcher.RunAsync(DispatcherPriority.Normal, 
    <lambda for your code which should run on the UI thread>);

That should work on both CP and later builds.

查看更多
弹指情弦暗扣
5楼-- · 2019-01-02 15:57

DispatcherTimer is also an option.

I used it for code that must be run in Xaml-designer (CoreWindow.Dispatcher,... are not available in UWP-designer)

var localTimer = new DispatcherTimer
{
    Interval = TimeSpan.FromMilliseconds(0)
};
localTimer.Tick += (timer, e) =>
{
    (timer as DispatcherTimer).Stop();
    action();
};
localTimer.Start();

Disclaimer:
I should note that this should be a last-resort option if every other fails.

查看更多
伤终究还是伤i
6楼-- · 2019-01-02 15:59

On UWP, I was having problem trying to set the Source property of CaptureElement control (that is defined in XAML), it was complaining about being prepared at different thread, even though I was trying to set it from code that was invoked via a Page_Loaded event handler. I ended up using this to work around it:

previewControl.Dispatcher.TryRunAsync(CoreDispatcherPriority.Normal, () => {
   previewControl.Source = _mediaCapture;
}).GetAwaiter().GetResult();
查看更多
何处买醉
7楼-- · 2019-01-02 16:02

This is a much easier way in my opinion.

Get the TaskScheduler associated with the UI.

    var UISyncContext = TaskScheduler.FromCurrentSynchronizationContext();

Then start a new Task and on the above UISyncContext.

    Task.Factory.StartNew(() => { /* Do your UI stuff here; */}, new System.Threading.CancellationToken(), TaskCreationOptions.PreferFairness, UISyncContext);
查看更多
登录 后发表回答