我正在使用TPL在MVVM应用程序中的后台线程上串行执行两个任务。在任务正在运行时,应用程序将显示一个“进度”对话框。因此,我的MVVM命令的Execute()
方法首先在主视图模型中引发ImageProcessingStarting
事件。该视图通过显示进度对话框来响应该事件。然后该命令启动第一个任务,继续执行第二个任务,并通过在主视图模型中引发ImageProcessingEnding
事件执行最后的“继续”。该视图通过关闭进度对话框来响应该事件。代码如下。继续执行几项任务
两个后台任务都正常执行,但进度对话框在第一个任务完成后提前关闭,而不是在第二个任务完成后关闭。我希望有人能告诉我为什么,以及如何解决这个问题。谢谢你的帮助。
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());
}
那么,如何让这些任务连续运行?谢谢。 –
@David Veeneman:我已根据您的意见更新了我的答案。 – fatty