MessageDialog ShowAsync 抛出 accessdenied 异常

MessageDialog ShowAsync throwing accessdenied exception

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();
}

我发现另一个用户 almost identical problem,但该页面上的每个解决方案都无法防止我的错误发生。他们的解决方案看起来像这样:

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();
});

一旦我发现问题出在从 MessageDialog 中打开 MessageDialog,我就能够使用此处实施的解决方案:

MessageDialog ShowAsync throws accessdenied exception on second dialog