使用任务实现BackgroundWorker的RunWorkerCompleted
我有一个 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
循环?
I have a WPF MVVM application. In one of the ViewModels, I have the following:
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.";
}
);
}
When I click the button bound to the GoCommand, I see the progress bar move from 1-100. When the ContinueWith executes DoSecondTask
, though, that task runs in the UI thread. How can I change the DoSecondTask
function to run the second for
loop in a new thread (or outside of the UI thread)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我在这个中找到了解决方案 答案。有趣的是,这个不起作用:
但是这个起作用:
I found the solution in this answer. It's interesting to note that this does not work:
But this does: