Using MessageDialog to show a message after Exception occurs

WinRT comes with a useful class called MessageDialog which can be used to show a simple modal dialog. However, per Microsoft’s design guideline, we should try to avoid using it unless we use it for urgent information or something that we really want our user to see it.

MessageDialog has a ShowAsync method which is used to show dialog asynchronously. We can put await operation before ShowAsync statement to make sure our code after it won’t be executed until our user close the dialog.

Here is how we can use it:

async void showDialog_Click(object sender, RoutedEventArgs e)
{
    var dlg = new MessageDialog("Modal Dialog");
    await dlg.ShowAsync();            

    // The code below won't be executed until our user close the dialog
    mainGrid.Background = new SolidColorBrush(Colors.Blue);
}

If we didn’t put await in the dlg.ShowAsync() line, the Grid’s background would change before user close the dialog.

One useful scenario that I think we could use MessageDialog is to show some message when there is an Exception in our app. However, await can’t be used in catch or finally block, so we can’t just do something like this.

catch (Exception ex)
{
    await new MessageDialog(exception.Message).ShowAsync();
}

Or we will get this compilation error, “Cannot await in the body of a catch clause”:

clip_image002

To resolve it, we can just grab the exception in catch block and use it with the await statement outside the catch block like this:

Exception exception;
try
{
    //... do something
}
catch (Exception ex)
{
    exception = ex;    
}

if(exception != null)
    await new MessageDialog(exception.Message).ShowAsync();

mainGrid.Background = new SolidColorBrush(Colors.Red);

Hope this helps someone! Enjoy coding.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s