I have a MessageDialog with just a single button in my App.xaml.cs I wish to use it from other pages. Several approaches seem to work but as there are subtleties with async and Tasks is a particular one correct?
The following is called with await App.mymessagebox("A message"):
public static Task async mymessagebox(string the_message)
{
MessageDialog messagedialog=new MessageDialog(the_message);
await messagedialog.ShowAsync();
}
The following is called with App the_app=(App)Application.current;
await the_app.mymessagebox("A message");:
public async Task mymessagebox(string the_message)
{
MessageDialog messagedialog=new MessageDialog(the_message);
await messagedialog.ShowAsync();
}
Both of these approaches are functionally equivalent, but the preferred solution would be not to put the methods in the
Appclass. Instead, you should create a separate class, which could be even static, that you would use to access these reusable message dialogs. The reason for this is that is separation of concerns.Appclass should only contain code related to the overall app initialization and lifecycle. This is a helper method simplifying the display of dialogs, so it should reside elsewhere:To adhere to the convention, you should add the
Asyncsuffix to the name of the method to make it clear the method isasyncand should beawaited.Calling this helper method will now look like this: