I have an MVVM application that processes a large number of images in the background, using the .NET 4.0 Task Parrallel Library. The processing is done on a background thread, which posts its progress to a view model property that is bound to a progress dialog. That part is working okay. But the background thread also needs to notify the main thread when all processing is done, so that the progress dialog can be closed.
Here's my dilemma: With my current code, the 'processing ending' statement gets hit as soon as the background task is set up. But if I insert a task.Wait()
statement between the two, it appears to block the UI thread, preventing progress updates. So, how does the background thread signal completion to the main thread? Thanks for your help.
Here is the code on the UI thread that creates the background task:
/* The view should subscribe to the two events referenced below, to
* show and close a progress indicator, such as a Progress dialog. */
// Announce that image processing is starting
m_ViewModel.RaiseImageProcessingStartingEvent();
// Process files as a background task
var task = Task.Factory.StartNew(() => DoWork(fileList, progressDialogViewModel));
// Announce that image processing is finished
m_ViewModel.RaiseImageProcessingEndingEvent();
And here is the DoWork()
method on the background thread. It processes the image files, using a Parallel.ForEach()
statement:
private void DoWork(IEnumerable<string> fileList, ProgressDialogViewModel viewModel)
{
// Declare local counter
var completedCount = 0;
// Process images in parallel
Parallel.ForEach(fileList, imagePath =>
{
ProcessImage(imagePath);
Interlocked.Increment(ref completedCount);
viewModel.Progress = completedCount;
});
}