加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 从TPL任务向WPF视图报告进度的适当方法是什么?

发布时间:2020-12-15 23:59:37 所属栏目:百科 来源:网络整理
导读:我试图从小的“块”或页面中读取数据库中的大量行,并将进度报告给用户;即,如果我在加载每个块时加载100个“块”报告进度. 我在C#4.0中使用TPL从数据库中读取这些块,然后将完整的结果集交给另一个可以使用它的任务.我觉得TPL让我能更好地控制任务取消和切换,
我试图从小的“块”或页面中读取数据库中的大量行,并将进度报告给用户;即,如果我在加载每个块时加载100个“块”报告进度.

我在C#4.0中使用TPL从数据库中读取这些块,然后将完整的结果集交给另一个可以使用它的任务.我觉得TPL让我能更好地控制任务取消和切换,而不是BackgroundWorker等,但似乎没有一种内置的方式来报告任务的进度.

这是我实现的向WPF进度条报告进度的解决方案,我想确保这是合适的,并且我应该采取更好的方法.

我首先创建了一个简单的界面来表示不断变化的进度:

public interface INotifyProgressChanged
{
  int Maximum { get; set; }
  int Progress { get; set; }
  bool IsIndeterminate { get; set; }
}

这些属性可以绑定到WPF视图中的ProgressBar,并且接口由支持ViewModel实现,后者负责启动数据加载并最终报告整体进度(本示例简化):

public class ContactsViewModel : INotifyProgressChanged
{
  private IContactRepository repository;

  ...

  private void LoadContacts()
  {
    Task.Factory.StartNew(() => this.contactRepository.LoadWithProgress(this))
      .ContinueWith(o => this.UseResult(o));
  }
}

您会注意到我将ViewModel作为INotifyProgressChanged传递给存储库方法,这是我想确保我没有做错的地方.

我的思考过程是,为了报告进度,实际执行工作的方法(存储库方法)需要访问INotifyProgressChanged接口,以报告最终更新视图的进度.这里快速浏览一下存储库方法(本例简述):

public class ContactRepository : IContactRepository
{
  ...

  public IEnumberable<Contact> LoadWithProgress(INotifyProgressChanged indicator)
  {
    var resultSet = new List<Contact>();
    var query = ... // This is a LINQ to Entities query

    // Set the maximum to the number of "pages" that will be iterated
    indicator.Maximum = this.GetNumberOfPages(query.Count(),this.pageSize);

    for (int i = 0; i < indicator.Maximum; i++)
    {
      resultSet.AddRange(query.Skip(i * this.pageSize).Take(this.pageSize));
      indicator.Progress += 1; // As each "chunk" is loaded,progress is updated
    }

    // The complete list is returned after all "chunks" are loaded
    return resultSet.AsReadOnly();
  }
}

这就是存储库最终通过ViewModel向View报告进度的方式.这是正确的方法吗?我是否正确使用TPL,违反任何主要规则等?这个解决方案正在运行,正在按预期报告进展情况,我只是想确保我没有为失败做好准备.

解决方法

执行此操作的“规定”方法是将 TaskScheduler实例从 TaskSheduler::FromCurrentSynchronizationContext传递到 ContinueWith,以确保在WPF调度程序线程上执行.

例如:

public void DoSomeLongRunningOperation()
 {
    // this is called from the WPF dispatcher thread

    Task.Factory.StartNew(() =>
    {
        // this will execute on a thread pool thread
    })
    .ContinueWith(t =>
    {
        // this will execute back on the WPF dispatcher thread
    },TaskScheduler.FromCurrentSynchronizationContext());
 }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读