Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call async method from PropertyChanged?

I have an WPF application based on MVVM architecture. I am implementing the common and widely used INotifyPropertyChanged interface on my ViewModels, because I need to react on user interaction.

But how do I perform an asynchronous action (e.g. loading some data) from within the synchronous PropertyChanged event handler without using async void 'hacks'?

Thanks in advance!

EDIT

The main reason why i need to avoid async void is because I am working in an test driven environment. Async void methods are not testable :(

like image 467
ˈvɔlə Avatar asked Oct 16 '25 15:10

ˈvɔlə


1 Answers

Actually, this is not about async void.

Usually you want to fire async operation and let your property setter return. Sample snippet:

private string carManufacturerFilter;

public string СarManufacturerFilter
{
    get { return carManufacturerFilter; }
    set
    {
        if (carManufacturerFilter != value)
        {
            carManufacturerFilter = value;
            OnPropertyChanged();

            // fire async operation and forget about it here;
            // you don't need it to complete right now;
            var _ = RefreshCarsListAsync();
        }
    }
}

private async Task RefreshCarsListAsync()
{
    // call some data service
    var cars = await someDataService.GetCarsAsync(carManufacturerFilter)
        .ConfigureAwait(false);

    // ...
}

Note, that there are a lot of things to add here:

  • since this is fire-and-forget approach, you need to block user input until operation is running. In other words, there should be some sort of busy indicator;
  • you may want to delay async operation firing. This is usually applicable, when there are string properties. You don't want to fire async operation after each char typed by user. Instead it's desirable to wait user to complete input;
  • there could be several properties, which fire the same async operation (imagine complex data filter). Some of them should fire operation immediately (e.g. checkbox), some of them need delay before firing;
  • you need to handle exceptions inside async method and display errors somehow.

P.S. I strongly recommend you to take a look at Reactive UI.

like image 130
Dennis Avatar answered Oct 18 '25 03:10

Dennis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!