How do I make this run asynchronously?

你离开我真会死。 提交于 2019-12-25 05:35:49

问题


I am writing a WPF application in C# and in it I need to query history in TFS, and I'm displaying the list of changesets I get back in a listview.

The listview ItemsSource is bound to an IEnumerable property called Changesets that is not loaded until the property is used:

public IEnumerable<Changeset> Changesets
{
  get
  {
    if (p_nChangesets == null)
    {
      p_nChangesets = TfsHelper.VCS.QueryHistory(Path, VersionSpec.Latest, 0,
                                                 RecursionType.Full, null,
                                                 new ChangesetVersionSpec(1),
                                                 VersionSpec.Latest, int.MaxValue, 
                                                 false, true, false, false)
                                                 .OfType<Changeset>();
    }
    return p_nChangesets;
  }
}

Now what happens is when the view loads, the listview is bound to this property so it immediately calls the property to get the collection of changesets. Sometimes this query runs slow so it takes a while to even see the window open. What I want to happen is the window displays immediately and the listview is empty until the changesets are found and then the listview is filled. But I don't know how to do this. I tried using a Task, but that had the same result:

public IEnumerable<Changeset> Changesets
{
  get
  {
    if (p_nChangesets == null)
    {
      Task<IEnumerable> task = Task<IEnumerable>.Run(() => TfsHelper.VCS.QueryHistory(
                                                           Path, VersionSpec.Latest, 0, 
                                                           RecursionType.Full, null,
                                                           new ChangesetVersionSpec(1),
                                                           VersionSpec.Latest, int.MaxValue, 
                                                           false, true, false, false));
      p_nChangesets = task.Result.OfType<Changeset>();
    }
    return p_nChangesets;
  }
}

Clearly, I don't know what I'm doing with tasks. Does anyone know how to make this do what I want?


回答1:


Add IsAsync=True in your binding in XAML:

<ListView ItemsSource="{Binding ChangeSets, IsAsync=True}"/>


来源:https://stackoverflow.com/questions/19501952/how-do-i-make-this-run-asynchronously

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!