MessageDialog 的 ShowAsync() 方法偶尔会失败。关于它是否有效,这几乎是一个硬币翻转:
private async Task CloseApp()
{
MessageDialog restartMessage = new MessageDialog("Changes have made a restart necessary.", "App must Restart")
restartMessage.Commands.Add(new UICommand("Close Application", (command) => { Application.Current.Exit(); }));
await restartMessage.ShowAsync(); // Code breaks here
Application.Current.Exit();
}
我发现另一个用户的问题几乎相同,但该页面上的每个解决方案都无法防止我的错误发生。他们的解决方案如下所示:
private async Task CloseApp()
{
IAsyncOperation<IUICommand> asyncCommand = null;
MessageDialog restartMessage = new MessageDialog("Changes have made a restart necessary.", "App must Restart")
restartMessage.Commands.Add(new UICommand("Close Application", (command) => { Application.Current.Exit(); }));
restartMessage.DefaultCommandIndex = 0;
asyncCommand = restartMessage.ShowAsync(); // Code *still* breaks here
Application.Current.Exit();
}
更新:
问题可能来自尝试在另一个 MessageDialog 调用的方法中在 MessageDialog 上运行 ShowAsync()。您不能同时显示两个 MessageDialog,因此会引发错误。
我使用 Dispatchers 的解决方案......实际上仍然无法正常工作,但无论如何都有一个问题:
MessageDialog restartMessage = new MessageDialog("Changes have made a restart necessary.", "App must Restart");
restartMessage.Commands.Add(new UICommand("Close Application", (command) => { Application.Current.Exit(); }));
CoreDispatcher cD = Window.Current.CoreWindow.Dispatcher;
await cD.RunAsync(CoreDispatcherPriority.Normal, async () =>
{
await restartMessage.ShowAsync();
});