我在这段代码中遇到了问题:
try { await DoSomethingAsync(); }
catch (System.UnauthorizedAccessException)
{
ResourceLoader resourceLoader = new ResourceLoader();
var accessDenied = new MessageDialog(resourceLoader.GetString("access_denied_text"), resourceLoader.GetString("access_denied_title"));
accessDenied.ShowAsync();
}
不可能写入 await accessDenied.ShowAsync(); 因为 Visual Studio 将其视为错误:在 Catch body 中禁止等待。但是没有等待的代码也不起作用。它无法捕获异常,并且应用崩溃。
无论如何,我需要同步显示此对话框,因为我需要在此时停止运行片刻。那么,该怎么做呢?
通常有一些方法可以重写代码以在 catch 块之外进行异步调用。至于不允许的原因,请检查此SO答案。将其移动到catch
块之外并添加await
基本上将使其"同步"。
所以,虽然它看起来很丑,但它应该是这样的:
bool operationSucceeded = false;
try
{
await DoSomethingAsync();
// in case of an exception, we will not reach this line
operationSucceeded = true;
}
catch (System.UnauthorizedAccessException)
{ }
if (!operationSucceeded)
{
var res = new ResourceLoader();
var accessDenied = new MessageDialog(
res.GetString("access_denied_text"),
res.GetString("access_denied_title"));
await accessDenied.ShowAsync();
}