2

我的视图模型是:

public class SampleViewModel : ViewModelBase
{
 private bool isBusy;
 public bool IsBusy
 {
   get { return isBusy; }
   set { isBusy = value;
         RaisePropertyChanged("IsBusy"); }

 private string prop1;
 public string Prop1
 {
   get { return prop1; }
   set { prop1 = value;
         RaisePropertyChanged("Prop1"); }
 }

 private string prop2;
 public string Prop2
 {
   get { return prop2; }
   set { prop2 = value;
         RaisePropertyChanged("Prop2"); }
 }

 private string prop3;
 public string Prop3
 {
   get { return prop3; }
   set { prop3 = value;
         RaisePropertyChanged("Prop3"); }
 }

 public SampleViewModel()
 {
     new Task(() => LoadProp1Async()).Start();
     new Task(() => LoadProp2Async()).Start(); 
     new Task(() => LoadProp3Async()).Start();
 }

 private void LoadProp1Async()
 {
    Thread.Sleep(5000);
    Prop1 = "a";
 }

 private void LoadProp2Async()
 {
    Thread.Sleep(15000);
    Prop2 = "b";
 }

 private void LoadProp3Async()
 {
    Thread.Sleep(10000);
    Prop3 = "c";
 }
}

看法:

<toolkit:BusyIndicator BusyText="Loading..." IsBusy="{Binding IsBusy}" />

我想在 viewmodel 属性 IsBusy == true 时显示 throbber。当三个任务中的任何一个正在运行时,此属性为真。

我怎样才能做到这一点?我个人有一个解决方案(使用调解器),但我不喜欢它。

4

1 回答 1

4

如果您使用的是 .NET 4.5,则可以使用 WhenAll 设置连接的延续:

 public SampleViewModel()
 {
    IsBusy = true;
    var task1 = Task.Run(() => LoadProp1Async());
    var task2 = Task.Run(() => LoadProp2Async());
    var task3 = Task.Run(() => LoadProp3Async());
    Task.WhenAll(task1, task2, task3).ContinueWith(t => IsBusy = false);
 }

如果不是,您可以在另一个任务中执行类似 WaitAll 的操作:

 public SampleViewModel()
 {
    IsBusy = true;
    new Task(() =>
    {
        var task1 = new Task(() => LoadProp1Async());
        var task2 = new Task(() => LoadProp2Async());
        var task3 = new Task(() => LoadProp3Async());
        task1.Start();
        task2.Start();
        task3.Start();
        Task.WaitAll(task1, task2, task3);
        IsBusy = false;
    }).Start();
 }
于 2013-02-12T05:28:49.510 回答