我的ViewModel是:
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。 当三个任务中的任何一个正在运行时,此属性为true。
我怎么能做到这一点? 我个人有一个解决方案(使用调解员),但我不喜欢它。
答案 0 :(得分: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();
}