Search code examples
c#asynchronousasync-awaituwpmessagedialog

Why await MessageDialog in Page constructor nevers ends?


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?


Solution

  • 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.