如何修改 MVVM View 模型的 Progress
属性以在后台线程上完成工作?
我正在使用 Task.Factory.StartNew()
和 Parallel.ForEach()
创建一个在后台线程上执行任务的 MVVM 应用程序。我正在使用 this article作为指南。到目前为止,我的代码如下所示:
Task.Factory.StartNew(() => DoWork(fileList, viewModel));
其中 fileList
是要处理的文件列表,viewModel
是具有 Progress
属性的 View 模型。到目前为止,DoWork()
方法如下所示:
private object DoWork(string[] fileList, ProgressDialogViewModel viewModel)
{
Parallel.ForEach(fileList, imagePath => ProcessImage(imagePath));
}
ProcessImage()
方法执行实际的图像处理。 View 模型的 Progress
属性绑定(bind)到对话框中的进度条,该对话框在后台进程开始之前显示。
我想在 Parallel.ForEach()
语句的每次迭代后更新 View 模型 Progress
属性。我需要做的就是增加属性值。我怎么做?感谢您的帮助。
最佳答案
由于该属性是一个简单的属性(而不是一个集合),您应该能够直接设置它。 WPF 将自动处理回 UI 线程的编码(marshal)处理。
但是,为了避免竞争条件,您需要明确处理“完成”计数器的递增。这可能是这样的:
private object DoWork(string[] fileList, ProgressDialogViewModel viewModel)
{
int done; // For proper synchronization
Parallel.ForEach(fileList,
imagePath =>
{
ProcessImage(imagePath));
Interlocked.Increment(ref done);
viewModel.Progress = done;
}
}
关于c# - MVVM 中的后台线程进度通知?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7237317/