Still getting my head around await/async, and am having difficulty seeing how I use it in an MVVM setting. I'm using MvvmLight, but I imagine the question applies to any other MVVM framework.
Suppose I have a WPF application that shows a list of pets. I have a RefreshCommand, that refreshes the list from a WCF service. The UI has an indicator to show that it's busy, and this is bound to an IsBusy bool property on the view model. My command code currently looks like this...
BackgroundWorker bw = new BackgroundWorker();
IsBusy = true;
bw.DoWork += (_, __) => {
Pets = _petService.GetPets();
IsBusy = false;
};
bw.RunWorkerAsync();
Pets is an ObservableCollection property on the view model.
I want to use the await/async keywords, and do away with the BackgroundWorker. I've searched and read, and read and searched, and am getting confused. Most of the articles/blog posts/etc I've seen seem to require you to create your own async implementation of ICommand. Why is this necessary? Given that MVVM and ICommand are built-in to the .NET framework, surely the ability to use async/await with them should also be built-in, without the need to create our own async command class.
Have I missed something, or is this really the only way to do it?
I tried the following, but it didn't work...
private async void LoadAsyncData() {
IsBusy = true;
Task<ObservableCollection<Pet>> t = GetPetsAsync();
Pets = await t;
IsBusy = false;
}
private async Task<ObservableCollection<Pet>> GetPetsAsync() {
await Task.Delay(1);
return _petService.GetPets();
}
I added the call to Task.Delay(1) as the compiler warned me that the method would be called sync.
The data loaded, but the UI never responded to the IsBusy property being changed, so the user doesn't see that the UI is busy.
Anyone able to advise?