如何在WinRT(Windows 8 Metro)上运行UI线程的代码?
Invoke
方法不存在。
如何在WinRT(Windows 8 Metro)上运行UI线程的代码?
Invoke
方法不存在。
直接从非 UI 线程获取 CoreWindow 更容易。以下代码将在任何情况下都有效,即使 GetForCurrentThread()
或 Window.Current
返回 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!
});
您需要引用 Windows.ApplicationModel.Core
命名空间:
using Windows.ApplicationModel.Core;
CoreApplication.MainView.CoreWindow.Dispatcher
对你无效?在尝试其他解决方案时,是否遇到了异常?Windows.UI.Core.CoreWindow.GetForCurrentThread().Dispatcher
?this.Dispatcher
? - CœurWindows.UI.Core.CoreWindow.GetForCurrentThread().Dispatcher
,但它也抛出了异常。我猜this.Dispatcher
在Windows.Runtime中不起作用。我已将其发布为单独的问题。 - NarenDeployment.Current.Dispatcher
。 - Cœur使用:
在您的UI线程中执行:
var dispatcher = Windows.UI.Core.CoreWindow.GetForCurrentThread().Dispatcher;
根据您的背景(非UI线程)
dispatcher.RunAsync(DispatcherPriority.Normal,
<lambda for your code which should run on the UI thread>);
这应该适用于 CP 和更高版本的构建。
CoreApplication.MainView.CoreWindow.Dispatcher
- eFloh使用:
this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => Frame.Navigate(typeof(Welcome), this));
对我来说它有效。
var UISyncContext = TaskScheduler.FromCurrentSynchronizationContext();
然后开始一个新任务,在上述的UISyncContext上。
Task.Factory.StartNew(() => { /* Do your UI stuff here; */}, new System.Threading.CancellationToken(), TaskCreationOptions.PreferFairness, UISyncContext);
previewControl.Dispatcher.TryRunAsync(CoreDispatcherPriority.Normal, () => {
previewControl.Source = _mediaCapture;
}).GetAwaiter().GetResult();
DispatcherTimer也是一个选择。
我在必须在Xaml设计器中运行的代码中使用它(CoreWindow.Dispatcher等在UWP设计器中不可用)。
var localTimer = new DispatcherTimer
{
Interval = TimeSpan.FromMilliseconds(0)
};
localTimer.Tick += (timer, e) =>
{
(timer as DispatcherTimer).Stop();
action();
};
localTimer.Start();
免责声明:
我应该指出,如果其他方法都失败了,这应该是最后的选择。