0

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?

RCP161
  • 199
  • 1
  • 13

1 Answers1

1

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

Geert van Horrik
  • 5,689
  • 1
  • 18
  • 32
  • I think I will end up with trying to migrate to async. All other workarounds seems to be hacks. The problem seems to be to call `.GetAwaiter().GetResult()` on a `await Dispatcher.BeginInvoke`. A realted question is [here](https://stackoverflow.com/questions/34549641/async-await-vs-getawaiter-getresult-and-callback) where this helpfull [post](https://blog.stephencleary.com/2016/12/eliding-async-await.html) is linked. Thanks for help! – RCP161 Aug 12 '20 at 13:09