c# - MVVM 中的后台线程进度通知?

标签 c# wpf multithreading mvvm

如何修改 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/

相关文章:

c# - 动态类型转换?

c# - 如何在 gridview 中动态添加页脚行。带文本框

c - 在 C 中终止一个线程

java - 设置读取器、解码器和消费者线程

c# - 无法在多个位置添加或插入项目 MyFile

c# - 如何将 Dispose 功能添加到 C# UserControl?

wpf - ListView.Items在ListView中始终为null作为ListViewItem-WPF

c# - 在 MeasureOverride(WPF 面板)中,当我没有固有的所需大小时,如何处理 availableSize 中的无穷大值?

c# - 触发属性更改后的wpf按钮命令绑定(bind)

c# - 如果 ThreadPool 线程死亡会发生什么?