If we want to inform the user about operation status which is running in the background by callback method, you have to be aware that the callback call is not in the UI thread. In this situation we cannot show Dialog message as ordinary, because we will go in trouble with cross-thread exception.
If we want to run eg. Dialog Message in Windows Store apps to inform user about operation status we need to run a “safe code”. This means we need to call Dispatcher, which cares that all calls related to UI components have to be from the main thread.
Lets assume we have callback method which gets call when user wants to see the payment status. Process of checking payment is not in UI thread, so the callback method of reporting status will also not be in the UI thread. In that situation, any code which touches UI must be executed with Dispatcher.
The following code shows how to create MessageDialog and show it in Windows Store app, so that the user get information about payment status.
/// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void PaymentCheckCompleted(object sender, PaymentEventArgs e) { MessageDialog dlg = null; if (e == null) { dlg = new MessageDialog("Status is NULL", "SMS Provider"); } else if (e.status == PaymentStatus.ok) { dlg = new MessageDialog("Status is OK", "SMS Provider"); } else if (e.status == PaymentStatus.cancelled) { dlg = new MessageDialog("Status is CANCELED", "SMS Provider"); } else if (e.status == PaymentStatus.failed) { dlg = new MessageDialog("Status is FAILED", "SMS Provider"); } else if (e.status == PaymentStatus.pending) { dlg = new MessageDialog("Status is PENDING", "SMS Provider"); } else { dlg = new MessageDialog("Status is UNKNOWN", "SMS Provider"); } dlg.Commands.Add(new UICommand("OK")); dlg.DefaultCommandIndex = 0; dlg.CancelCommandIndex = 0; dlg.Options = MessageDialogOptions.None; this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => dlg.ShowAsync()); }
The last line in the example above shows how to use Dispatcher, and how to show dialog so that we never see cross-thread exception.
Your post is so good to read. Excellent!!
Thank you very much for sharing, I would like to post it on my Tumblr to share with my friends?
Thanks, but this solution gives Warning :( that “await” not used in last line
Yes you are right, this post just show usage of the Dispatcher.
But here is a working source code:
private async void PaymentCheckCompleted(object sender, EventArgs e)
{
Windows.UI.Popups.MessageDialog dlg = new MessageDialog(“This is content of the dialog.”, “Dialog title!”);
dlg.Commands.Add(new UICommand(“OK”));
dlg.DefaultCommandIndex = 0;
dlg.CancelCommandIndex = 0;
dlg.Options = MessageDialogOptions.None;
await this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
var retVal= dlg.ShowAsync();
});
}
Aparneptly this is what the esteemed Willis was talkin’ ’bout.