简体   繁体   中英

How to show MessageDialog synchronously in windows 8 app?

I have a problem in this code:

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

It impossible to write await accessDenied.ShowAsync(); because Visual Studio count it as error: awaiting is forbidden in Catch body. But code without await doesn't work too. It can't catch an exception and app crashes.

Anyway, I need to show this dialog synchronously, because I need to stop running at this point for a moment. So, how to do this?

There are usually ways to rewrite the code to have async calls outside of the catch block . As for reasons why it's not allowed, check this SO answer . Moving it outside the catch block and adding await will basically make it "synchronous".

So, although it looks ugly, it should be something like:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM