catching exception thrown by ContentDialog::ShowAsync in C++/WinRT

572 Views Asked by At

In C++/CX i had:

IAsyncOperation<ContentDialogResult> Dialog::show() {
    return dialog_.ShowAsync();
}

If I create and try to show two dialogs and as a result show() gets called twice, ShowAsync used to throw an exception:

Only a single ContentDialog can be open at any time

which I used to catch and handle this case. When I am converting this code to C++/WinRT, based on my understanding of the conversion rules, have:

IAsyncOperation<ContentDialogResult> Dialog::show() {
    co_return co_await dialog_.ShowAsync();
}

The caller looks like this:

void Dialog::caller(){
    .....
    try {
        show();
    } catch (winrt::hresult_error err) {
        handle.....
        return;
    }
    ......
    ......
}

I do see a windows exception being thrown, but somehow it is not caught by my code.

Is this the right way of calling ShowAsync()? And how can I handle this exception?

1

There are 1 best solutions below

2
On

Only one ContentDialog can be shown at a time.

When you call the show() twice directly, the second dialog will try to display as soon as the first dialog is displayed. It will not wait for the first dialog to close before displaying, so this exception will be thrown.

If you want to show two dialogs one by one, you need to wait for the first dialog operation to complete before showing the second one. For example:

For C++/CX, you could try to use task class to consume an async operation.

IAsyncOperation<ContentDialogResult>^ ShowDialogSample::MainPage::Show()
{
    return dialog->ShowAsync();
}

void MainPage::CallerFunction()
{
    auto ShowTask = create_task(Show());
    ShowTask.then([this](ContentDialogResult result)
    {
        ...... 
        Show();
    });
}

For C++/WinRT, you could use co_await statement to cooperatively await the result of the function and then continue to the next step.

IAsyncOperation<ContentDialogResult> MainPage::Show()
{
    co_return co_await dialog.ShowAsync();
}

IAsyncAction MainPage::CallerFunction()
{      
    ......
    co_await Show();
    co_await Show();     
    ......
}