1

I need to wait the result of a MessageDialog when my UWP application starts, during the splash screen. So, I put this MessageDialog inside the MainPage constructor:

private async Task ParseConfiguration()
{
    var dialog = new MessageDialog("Message", "Title");
    dialog.Commands.Add(new UICommand { Label = "Exit", Id = 0 });

    await dialog.ShowAsync();
}


public MainPage()
{
    ParseConfiguration();   // works, but I need to wait
    ParseConfiguration().Wait(); // never exits this call
}

How can I fix this problem?

Nick
  • 10,309
  • 21
  • 97
  • 201
  • You can move whatever you want to do after dialog is shown to continuation of that task: ParseConfiguration().ContinueWith(t => {... do stuff here... }); – Evk Jun 07 '16 at 12:06
  • 1
    Please check this post: http://blogs.msdn.com/b/pfxteam/archive/2011/01/13/10115163.aspx – Daniel Krzyczkowski Jun 07 '16 at 12:07
  • @Evk ok, but I still need to wait the result of my async Task. – Nick Jun 07 '16 at 12:15
  • 1
    Take a look at this: http://blog.stephencleary.com/2013/01/async-oop-2-constructors.html – Yacoub Massad Jun 07 '16 at 12:16
  • @Evk Because for example if I can't read the configuration I want the application to exit. And there is not ConfigureAwait method on UWP. – Nick Jun 07 '16 at 12:20

1 Answers1

1

You are blocking your UI thread by waiting on that task, so dialog (which obviously also needs UI thread to be shown) cannot be shown and whole thing deadlocks. However, page constructor is not a good place to do this anyway (and constructors in general). Instead (for example, this is not the only place) you can do this in Application.OnLaunched:

protected override async void OnLaunched(LaunchActivatedEventArgs e) {
    // some other code here
    // parse configuration before main window is shown
    await ParseConfiguration();
    // some more code here, including showing main windo
}

This will your dialog will be shown during splash screen, but before main page is shown (as you want). You can also terminate whole application at this point if something goes wrong.

Evk
  • 98,527
  • 8
  • 141
  • 191