在WinRT中的UI线程上运行代码

如何在WinRT(Windows 8 Metro)中的UI线程上运行代码?

Invoke方法不存在。


蛊毒传说
浏览 600回答 3
3回答

红颜莎娜

从非UI线程直接获取CoreWindow更容易。以下代码可以在任何地方使用,即使是GetForCurrentThread()或Window.Current返回null。CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,&nbsp; &nbsp; <lambda for your code which should run on the UI thread>);例如:CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,&nbsp; &nbsp; () =>&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; // Your UI update code goes here!&nbsp; &nbsp; });您需要引用Windows.ApplicationModel.Core命名空间:using Windows.ApplicationModel.Core;

当年话下

使用:从您的UI线程,执行:var dispatcher = Windows.UI.Core.CoreWindow.GetForCurrentThread().Dispatcher;从你的背景(非UI线程)dispatcher.RunAsync(DispatcherPriority.Normal,&nbsp;&nbsp; &nbsp; <lambda for your code which should run on the UI thread>);这应该适用于CP和后期版本。

蓝山帝景

在我看来,这是一种更容易的方法。获取与UI关联的TaskScheduler。&nbsp; &nbsp; var UISyncContext = TaskScheduler.FromCurrentSynchronizationContext();然后在上面的UISyncContext上启动一个新任务。&nbsp; &nbsp; Task.Factory.StartNew(() => { /* Do your UI stuff here; */}, new System.Threading.CancellationToken(), TaskCreationOptions.PreferFairness, UISyncContext);
打开App,查看更多内容
随时随地看视频慕课网APP