In a Windows 8 Style app, I have the following code which is retrieving a list of files in a custom FileService. This is being fired in the Constructor of a ViewModel.
private async void Construct()
{
Files = new ObservableCollection<FileViewModel>();
IList _files = await _fileRepository.GetFiles();
foreach (File file in _files)
{
Files.Add(new FileViewModel(file));
}
}
It works perfectly, but what I am struggling to figure out is how I would perform Progress reporting on this to inform the user that something is happening while the files are being loaded.
Looking at it, I would like to have a bool IsBusy property which I could bind to something like a ProgressRing on the View. I get that I could set to this to true when the process starts but how can I get a Completed callback from operation where I could then set this property to False?
Many thanks!
First off, I think you shouldn't use async void
methods (unless they are event handlers, of course). "Asynchronous constructors" are best implemented as a static async
factory method or with asynchronous lazy initialization (explained on my blog). Both of these approaches are better than async void
.
Now, on to progress reporting. The Task-based Asynchronous Programming document describes the recommended way of reporting progress, and my AsyncEx library includes an IProgress<T>
implementation called PropertyProgress
specifically for treating progress updates as ViewModel observable properties.
However, it sounds like you just need a "busy indicator", not a full "progress report". This is quite a bit simpler:
private async Task Construct()
{
Files = new ObservableCollection<FileViewModel>();
IsBusy = true;
IList _files = await _fileRepository.GetFiles();
IsBusy = false;
foreach (File file in _files)
{
Files.Add(new FileViewModel(file));
}
}
In this example, I'm assuming that the IsBusy
setter will raise INotifyPropertyChanged.PropertyChanged
appropriately.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.