Current thread notification in MVVM?

How do I change the MVVM view model Progress property to work in the background thread?

I am creating an MVVM application that performs a task in a background thread using Task.Factory.StartNew() and Parallel.ForEach() . I use this article as a guide. So far, my code looks like this:

 Task.Factory.StartNew(() => DoWork(fileList, viewModel)); 

Where fileList is the list of files to process, and viewModel is the view model with the Progress property. The DoWork() method looks like this:

 private object DoWork(string[] fileList, ProgressDialogViewModel viewModel) { Parallel.ForEach(fileList, imagePath => ProcessImage(imagePath)); } 

The ProcessImage() method performs the actual processing of the image. The Progress property of the view model is tied to the execution line in the dialog box that appears immediately before the background process begins.

I want to update the property of the Progress view model after each iteration of the Parallel.ForEach() statement. All I have to do is increase the value of the property. How can I do it? Thank you for your help.

+7
source share
1 answer

Since a property is a simple property (not a collection), you should be able to set it directly. WPF will automatically process marshaling back into the user interface thread.

However, to avoid race conditions, you need to handle the increment of your "made" counter explicitly. It could be something like:

 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; } } 
+7
source

All Articles