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 :(
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:
P.S. I strongly recommend you to take a look at Reactive UI.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With