【发布时间】:2011-05-24 15:00:07
【问题描述】:
我有一个 WPF MVVM 应用程序。在其中一个 ViewModel 中,我有以下内容:
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 循环?
【问题讨论】:
标签: .net c#-4.0 backgroundworker task