I am working on an MVVM application that performs several tasks in the background using TPL. Tasks must report progress in the user interface so that the progress dialog can be updated. Because the application is MVVM, the progress dialog is tied to a property of the view model called Progress, which is updated using the view model method with the signature UpdateProgress(int increment)
. Background tasks should call this method to report progress.
I use the method to update the property, because it allows each task to increase the Progress property by different amounts. So, if I have two tasks, and the first takes four times to the second, the first task calls UpdateProgress(4)
, and the second task calls UpdateProgress(1)
. Thus, progress reaches 80% upon completion of the first task and at 100% upon completion of the second task.
My question is very simple: how do I call the view model method from my background tasks? The code is below. Thank you for your help.
The tasks use Parallel.ForEach()
, in code that looks like this:
private void ResequenceFiles(IEnumerable<string> fileList, ProgressDialogViewModel viewModel) { // Wrap token source in a Parallel Options object var loopOptions = new ParallelOptions(); loopOptions.CancellationToken = viewModel.TokenSource.Token; // Process images in parallel try { Parallel.ForEach(fileList, loopOptions, sourcePath => { var fileName = Path.GetFileName(sourcePath); if (fileName == null) throw new ArgumentException("File list contains a bad file path."); var destPath = Path.Combine(m_ViewModel.DestFolder, fileName); SetImageTimeAttributes(sourcePath, destPath); // This statement isn't working viewModel.IncrementProgressCounter(1); }); } catch (OperationCanceledException) { viewModel.ProgressMessage = "Image processing cancelled."; } }
The viewModel.IncrementProgressCounter(1)
statement does not throw an exception, but does not go to the main thread. Tasks are called from MVVM ICommand
objects in code that looks like this:
public void Execute(object parameter) { ...
source share