我在此代码中有问题:
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();
}
不可能写一个等待accessDenied.ShowAsync(); 因为Visual Studio将其视为错误:在Catch主体中禁止等待。但是,没有等待的代码也无法正常工作。它无法捕获异常,导致应用崩溃。
无论如何,我需要同步显示此对话框,因为我需要暂时停止运行。那么,该怎么做呢?
通常,有多种方法可以重写代码以在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();
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句