Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Background thread progress notification in MVVM?

How do I modify an MVVM view model Progress property for work being done on a background thread?

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

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

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

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

The ProcessImage() method does the actual image processing. The view model's Progress property is bound to a progress bar in a dialog that is displayed just before the background process begins.

I'd like to update the view model Progress property after each iteration of the Parallel.ForEach() statement. All I need to do is increment the property value. How do I do that? Thanks for your help.

like image 331
David Veeneman Avatar asked Aug 29 '11 23:08

David Veeneman


1 Answers

Since the property is a simple property (and not a collection), you should be able to set it directly. WPF will handle the marshaling back to the UI thread automatically.

However, in order to avoid a race condition, you'll need to handle the incrementing of your "done" counter explicitly. This 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;
       }
}
like image 141
Reed Copsey Avatar answered Oct 27 '22 08:10

Reed Copsey