暂停代码的执行,但不暂停应用程序

Halt code's execution, but not the application

首先是代码,它运行没有错误,但没有涵盖我需要的所有内容:

public async Task SaveData()
{
    // MessageDialog restartMessage;
    // ^^ This was made global and is defined in SafeToSave()

    // Check if it's safe to save
    await SafeToSave();
    if (restartMessage != null)
    {
        CoreDispatcher cD = Window.Current.CoreWindow.Dispatcher;
        await cD.RunAsync(CoreDispatcherPriority.Normal, async () =>
        {
            await restartMessage.ShowAsync();
            // This WILL invoke 'Application.Current.Exit()'
        });

        return;
        // Issue is right around here...
    }

    // Other code...

}

基本前提是如果保存不安全,消息对话框会告诉用户需要重新启动应用程序,然后在他们点击 'Okay' 时执行 'Application.Current.Exit()'按钮。

我的问题是我需要我的代码在重启时停止执行。现在'return'只结束了这个方法,但是之后它会继续在调用SaveData()的方法中做其他事情,直到我的restartMessage生效,这样不好。

我考虑过将 'Application.Current.Exit()' 置于 'return' 语句之上,但这会在看到我的错误消息之前关闭所有内容。这也不好。

另一种解决方案是跳过整个 CoreDispatcher 事情,只跳过 运行 ShowAsync() 本身,除非那样会触发不同的已知错误。基本上,我有一些调用 SaveData() 方法的 MessageDialog,并且在另一个 MessageDialog 已经打开时打开一个 MessageDialog 同样不好。

就是这样:我需要一些东西来停止我的代码表单的执行,而不会终止整个应用程序或阻止我的错误消息显示。我能做什么?

简短版,我使用了这个人的解决方案:MessageDialog ShowAsync throws accessdenied exception on second dialog

由于我无法控制Dispatcher 何时发生,因此有必要将其废弃。现在我说我不能那样做,因为它正在防止另一个错误,所以我使用 link 中的建议以不同的方式防止该错误......所以现在我可以放弃 Dispatcher 并强制我的应用程序处理我的消息对话框,而不是继续沿着它的多线程路径做它不应该做的事情!

我的解决方案代码已移至 SafeToSave() 方法中。我做了那个 link 中的那个人所做的,然后改变了这个:

CoreDispatcher cD = Window.Current.CoreWindow.Dispatcher;
await cD.RunAsync(CoreDispatcherPriority.Normal, async () =>
{
    await restartMessage.ShowAsync();
});

进入这个:

await restartMessage.ShowAsync();

与之前不同的是,当另一个 MessageDialog 已经启动时,我没有收到调用 ShowAsync() 的访问错误,因为我先强行关闭了它。