I am trying to show a WinUI dialog - i.e. a class that derives from ContentDialog - from code that executes from a background thread and I need to wait for the result of the dialog.
I know that showing a dialog from a background thread is only possible with some kind of dispatcher that dispatches this code back to the UI thread.
This is the method that shows my dialog in its current form:
public async Task<MyDialogResult> ShowMyDialogAsync(MyViewModel viewModel, string primaryButtonText, string closeButtonText)
{
// EXCEPTION OCCURS HERE WHEN CALLING FROM NON UI-THREAD
MyDialog dialog = new MyDialog(); // This class derives from ContentDialog
// Set dialog properties
dialog.PrimaryButtonText = primaryButtonText;
dialog.CloseButtonText = closeButtonText;
dialog.ViewModel = viewModel;
dialog.XamlRoot = _xamlRoot;
await dialog.ShowAsync();
return dialog.ViewModel.MyDialogResult;
}
Please note that I need some result from this dialog which is entered by the user. That is why the method has a return value of Task<MyDialogResult>
.
While doing my research I came across this answer, which refers to the article Await a UI task sent from a background thread from Microsoft.
There they use a method RunAsync
which gets transformed into a method RunTaskAsync<T>
.
The RunAsync
method can be found on the CoreDispatcher class.
My problem is: I am unable to try this approach, because the CoreDispatcher property seems always to be null at runtime when accessing it (from my MainWindow class for example). Here is a screenshot of my MainWindow instance during runtime:
According to this article, "Dispatcher" being null seems to be a design choice.
The only similar property available is a DispatcherQueue. But this only has the method TryEnqueue. But I do not know how to use it in they way I need, which is not only to execute the code on the UI thread but also wait for its completion, so code can run after it in a controlled manner.
Does anyone know how an approach how to show in WinUI ContentDialog
using some kind of dispatcher and wait for the result of the dialog?