Only one MessageDialog may be displayed

On Windows 8, a call to "await aMessageDialog.ShowAsync()" can only be made once, otherwise System.UnauthorizedAccessException will be thrown (E_ACCESSDENIED 80070005). This is a helper method to display dialogs although it's not thread-safe. It's inspired on StackOverflow answers:

  1. public static class DialogDisplayer {
  2. private static IAsyncOperation currentlyShownDialog;
  3.  
  4. public static async Task TryToShowDialog(MessageDialog messageDialog){
  5. try{
  6. RequestPreviousDialogCancelation();
  7. await WaitForUIThreadToBeReady();
  8. await ShowDialog(messageDialog);
  9. }
  10. catch (TimeoutException ex){
  11. //Logger.Information("Time out waiting for a MessageDialog to be closed");
  12. }
  13. catch (TaskCanceledException ex){
  14. CancelDialog();
  15. }
  16. catch (UnauthorizedAccessException ex){
  17. //Logger.Information("Multiple dialogs are being opened at the same time. There is a direct call to ShowAsync somewhere. Instead of using ShowAsync, use this method");
  18. }
  19. }
  20.  
  21. private static void CancelDialog(){
  22. currentlyShownDialog = null;
  23. }
  24.  
  25. private static void RequestPreviousDialogCancelation(){
  26. if (IsThereAnyOpenedDialog()){
  27. currentlyShownDialog.Cancel();
  28. }
  29. }
  30.  
  31. private static async Task ShowDialog(MessageDialog messageDialog){
  32. currentlyShownDialog = messageDialog.ShowAsync();
  33. await currentlyShownDialog;
  34. }
  35.  
  36. private static async Task WaitForUIThreadToBeReady(){
  37. var attempts = 0;
  38. while (IsThereAnyOpenedDialog()){
  39. await Task.Delay(TimeSpan.FromMilliseconds(100));
  40. attempts++;
  41. if (attempts > 5){
  42. throw new TimeoutException();
  43. }
  44. }
  45. }
  46.  
  47. private static bool IsThereAnyOpenedDialog(){
  48. return currentlyShownDialog != null && currentlyShownDialog.Status == AsyncStatus.Started;
  49. }
  50. }
  51.  

Usage:

  1. var messageDialog = new MessageDialog("Hello world");
  2. await DialogDisplayer.TryToShowDialog(messageDialog);
  3.  
Enjoyed reading this post?
Subscribe to the RSS feed and have all new posts delivered straight to you.