简体   繁体   English

Windows 8 Store App中异步方法的进度报告

[英]Progress Reporting from an Async method in a Windows 8 Store App

In a Windows 8 Style app, I have the following code which is retrieving a list of files in a custom FileService. 在Windows 8 Style应用程序中,我有以下代码正在检索自定义FileService中的文件列表。 This is being fired in the Constructor of a ViewModel. 这是在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. 看着它,我想拥有一个bool IsBusy属性,可以将它绑定到诸如View上的ProgressRing之类的东西。 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? 我知道可以在过程开始时将其设置为true,但是如何从操作中获取Completed回调,然后可以将该属性设置为False?

Many thanks! 非常感谢!

First off, I think you shouldn't use async void methods (unless they are event handlers, of course). 首先,我认为您不应该使用async void方法(当然,除非它们是事件处理程序)。 "Asynchronous constructors" are best implemented as a static async factory method or with asynchronous lazy initialization (explained on my blog). 最好将“异步构造函数”实现为静态async工厂方法或异步惰性初始化 (在我的博客中进行了解释)。 Both of these approaches are better than async void . 这两种方法都比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. 基于任务的异步编程文档描述报告进展情况的推荐方式,而我AsyncEx库包括IProgress<T>称为实施PropertyProgress专门用于治疗最新进展为视图模型观察到的性能。

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. 在此示例中,我假设IsBusy设置程序将适当地引发INotifyPropertyChanged.PropertyChanged

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM