【发布时间】:2011-09-06 17:59:10
【问题描述】:
我正在开发一个使用 TPL 在后台执行多项任务的 MVVM 应用程序。任务需要向 UI 报告进度,以便可以更新进度对话框。由于应用程序是 MVVM,因此进度对话框绑定到名为 Progress 的视图模型属性,该属性由带有签名 UpdateProgress(int increment) 的视图模型方法更新。后台任务需要调用该方法上报进度。
我使用一种方法来更新属性,因为它允许每个任务将 Progress 属性增加不同的数量。所以,如果我有两个任务,第一个任务的时间是第二个的四倍,第一个任务调用UpdateProgress(4),第二个任务调用UpdateProgress(1)。因此,第一个任务完成时进度为 80%,第二个任务完成时进度为 100%。
我的问题非常简单:如何从后台任务中调用视图模型方法?代码如下。感谢您的帮助。
任务使用Parallel.ForEach(),代码如下:
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.";
}
}
语句viewModel.IncrementProgressCounter(1) 没有抛出异常,但它没有进入主线程。这些任务是从 MVVM ICommand 对象调用的,代码如下所示:
public void Execute(object parameter)
{
...
// Background Task #2: Resequence files
var secondTask = firstTask.ContinueWith(t => this.ResequenceFiles(fileList, progressDialogViewModel));
...
}
【问题讨论】:
标签: mvvm task-parallel-library