splash27
splash27

Reputation: 2107

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?

Upvotes: 0

Views: 1086

Answers (1)

vgru
vgru

Reputation: 51204

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

Upvotes: 1

Related Questions