I am using TPL to perform two tasks serially on a background thread in an MVVM app. While the tasks are running, the app displays a Progress dialog. So, my MVVM command’s Execute() method first raises an ImageProcessingStarting event in the main view model. The view responds to the event by displaying the Progress dialog. The command then launches the first task, continues with the second task, and performs the final ‘continue with’ by raising an ImageProcessingEnding event in the main view model. The view responds to the event by closing the Progress dialog. The code is below.
Both background tasks are executing properly, but the Progress dialog is closing early, after the first task completes, instead of after the second one. I am hoping someone can tell me why, and how to fix the problem. Thanks for your help.
public void Execute(object parameter)
{
...
// Announce that image processing is starting
m_ViewModel.RaiseImageProcessingStartingEvent();
// Set up a cancellation token source
var tokenSource = new CancellationTokenSource();
m_ViewModel.ProgressDialogViewModel.TokenSource = tokenSource;
// Background Task #1: Add time stamps to files
var task = Task.Factory.StartNew(() => this.AddTimeStampsToFiles(fileList, progressDialogViewModel));
/* The Progress dialog is closing at this point! */
// Background Task #2: Resequence files
task.ContinueWith(t => this.ResequenceFiles(fileList, progressDialogViewModel));
/* The Progress dialog should close at this point. */
// Announce that image processing is finished
task.ContinueWith(t => m_ViewModel.RaiseImageProcessingEndingEvent(), TaskScheduler.FromCurrentSynchronizationContext());
}
According to MSDN
Which means that when the main task finishes, the other items in your two ContinueWith calls will run in parallel with one another.
To demonstrate this, you use the code below:
The Output Window will then read:
To help you out in your question, I have always used the
System.ComponentModel.BackgroundWorkerto run tasks serially. There are probably better ways, but this works for me for now.For this to work, you may need to pass the
fileListandprogressDialogViewModelvalues in to thebgW.RunWorkerAsync()method.For multiple values, I typically use a
Dictionary<string, object>object so I can refer to the values by name.Hope this helps.