【问题标题】:How to show MessageDialog synchronously in windows 8 app?如何在 Windows 8 应用程序中同步显示 MessageDialog?
【发布时间】:2013-09-17 21:19:21
【问题描述】:

这段代码有问题:

 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 正文中禁止等待。但是没有等待的代码也不起作用。它无法捕获异常和应用程序崩溃。

无论如何,我需要同步显示这个对话框,因为此时我需要停止运行一会儿。那么,该怎么做呢?

【问题讨论】:

    标签: c# .net-4.5


    【解决方案1】:

    通常有一些方法可以将代码重写为async calls outside of the catch block。至于不允许的原因,请查看this SO answer。将其移出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();       
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多