1
我有一个WPF MVVM应用程序。在的ViewModels之一,我有以下几点:使用任务实现BackgroundWorker的RunWorker
this.GoCommand = new RelayCommand(() =>
{
var scheduler = TaskScheduler.FromCurrentSynchronizationContext();
Task.Factory.StartNew(() =>
{
for (int i = 0; i < 100; ++i)
{
this.Progress = i + 1;
Thread.Sleep(30);
}
}).ContinueWith(task =>
{
// should act like RunWorkerCompleted
this.DoSecondTask();
},
scheduler
);
});
private void DoSecondTask()
{
Task.Factory.StartNew(() =>
{
for (int i = 0; i < 100; ++i)
{
// repeated task for simplicity
this.Progress = i + 1;
Thread.Sleep(30);
}
}).ContinueWith(task =>
{
this.Status = "Done.";
}
);
}
当我点击绑定到GoCommand按钮,我看到从1-100进度条举措。但是,当ContinueWith执行DoSecondTask
时,该任务将在UI线程中运行。如何更改DoSecondTask
函数以在新线程(或UI线程之外)中运行第二个for
循环?