开发者

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 li开发者_Python百科ke 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.


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;
       }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜