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
循環?