Question on how to show a modal dialog synchronously
See original GitHub issueIn WPF, the Window.ShowDialog();
method blocks the thread and continues when the dialog is closed (the same way MessageBox.Show();
works in WinForms). In Avalonia, the docs indicate that Window.ShowDialog()
executes asynchronously, meaning the thread can continue before the dialog is closed.
Maybe this is a matter of me not being good at async vs sync coding but how would I produce a similar result to WPF/WinForms but using the way Avalonia has been architected? I want to call ShowDialog
from a non-async method and have execution pause until the dialog is closed.
I’ve tried the following:
Task.WhenAll(dialog.ShowDialog(parent));
, dialog.ShowDialog(parent).Result;
, and dialog.ShowDialog(parent).Wait();
block the dialog thread and prevents the dialog from loading.
Task.Run(() => ShowDialog()).GetAwaiter().GetResult();
private async Task ShowDialog()
{
Dialog dialog = new Dialog();
await dialog.ShowDialog(parent);
}
throws an exception of System.InvalidOperationException: ‘Call from invalid thread’
What is the proper way to do this?
Issue Analytics
- State:
- Created 3 years ago
- Comments:19 (8 by maintainers)
A workaround (adapted from https://github.com/AvaloniaUI/Avalonia/issues/857#issuecomment-272927078) is this:
https://github.com/jp2masa/dotnet-properties/blob/4584f2f4245d999eb270ece5ec013f9f97c0f8bf/src/dotnet-properties/Services/DialogService.cs#L28-L32
It will block until the dialog closes.
@derekantrican if that works fine for you and you use it for multiple windows, consider making extension to ease your code. Something like: