catel

Catel call ShowDialogAsync sync


I try to call ShowDialogAsync in a synchron code. I'm not very familiar with async programming. If I run this code, I end up in a deadlock. If I change Command to TaskCommand, it will work, but I have to change all Code to async.

    public MainWindow()
    {
        InitializeComponent();
        Abc = new Command(() => Asd());
    }

    public Command Abc { get; set; }

    private void Asd()
    {
        var b = StartDialog(true).GetAwaiter().GetResult();
    }

    private async Task<bool> StartDialog(bool isMultiple)
    {
        await ServiceLocator.Default.ResolveType<IUIVisualizerService>().ShowDialogAsync<PersonVm>(new PersonM());
        return true;
    }

Here I have used the answer from here. Could someone help me please?


Solution

  • The recommended way is to migrate your code to async. Most features in Catel are async (such as vm initialization, etc). At first it might be a bit overwhelming, but once you get how it works, it's a very convenient way of programming. In the meantime, you can use a workaround (this is not best practice, but will get you through this task):

        private async void Asd()
        {
            var b = await StartDialog(true);
        }
    

    Note that async void is not recommended and should really be avoided unless no other options are available (such as non-async event handlers, etc).