Mvvm 继续执行若干任务
我使用TPL在MVVM应用程序的后台线程上连续执行两个任务。当任务运行时,应用程序会显示一个进度对话框。因此,我的MVVM命令的Mvvm 继续执行若干任务,mvvm,task-parallel-library,Mvvm,Task Parallel Library,我使用TPL在MVVM应用程序的后台线程上连续执行两个任务。当任务运行时,应用程序会显示一个进度对话框。因此,我的MVVM命令的Execute()方法首先在主视图模型中引发一个ImageProcessingStarting事件。视图通过显示“进度”对话框来响应事件。然后,该命令启动第一个任务,继续执行第二个任务,并通过在主视图模型中引发imageprocessingding事件来执行最终的“继续”。视图通过关闭“进度”对话框来响应事件。代码如下 两个后台任务都正常执行,但进度对话框在第一个任务完
Execute()
方法首先在主视图模型中引发一个ImageProcessingStarting
事件。视图通过显示“进度”对话框来响应事件。然后,该命令启动第一个任务,继续执行第二个任务,并通过在主视图模型中引发imageprocessingding
事件来执行最终的“继续”。视图通过关闭“进度”对话框来响应事件。代码如下
两个后台任务都正常执行,但进度对话框在第一个任务完成后提前关闭,而不是在第二个任务完成后关闭。我希望有人能告诉我为什么,以及如何解决这个问题。谢谢你的帮助
据 任务。继续使用方法 创建一个继续,当目标 任务完成 这意味着当主任务完成时,两个ContinueWith调用中的其他项将并行运行 要演示这一点,请使用以下代码:
System.Threading.Tasks.Task task = new System.Threading.Tasks.Task(() => Console.WriteLine("1"));
task.ContinueWith((t) => { System.Threading.Thread.Sleep(1000); Console.WriteLine("2"); });
task.ContinueWith((t) => Console.WriteLine("3"));
然后,输出窗口将显示:
1
3
2
为了帮助您解决问题,我一直使用System.ComponentModel.BackgroundWorker
连续运行任务。也许有更好的方法,但这对我来说暂时有效
public void Execute(object parameter)
{
BackgroundWorker bgW = new BackgroundWorker();
bgW.DoWork += (s, args) =>
{
AddTimeStampsToFiles(fileList, progressDialogViewModel);
ResequenceFiles(fileList, progressDialogViewModel);
};
bgW.RunWorkerCompleted += (s, args) =>
{
m_ViewModel.RaiseImageProcessingEndingEvent();
};
m_ViewModel.RaiseImageProcessingStartingEvent();
bgW.RunWorkerAsync();
}
为此,您可能需要将fileList
和progressDialogViewModel
值传递到bgW.RunWorkerAsync()
方法
对于多个值,我通常使用字典
对象,以便按名称引用这些值
希望这有帮助。找到了我的答案。在我的原始代码中,第二个和第三个任务都是第一个任务的延续。我更改了代码,为原始任务(
taskOne
)和后续任务(taskTwo
和taskTwo
)创建了单独的任务。然后,taskTwo
继续taskOne
,而taskThree
继续taskTwo
,如下所示:
// Background Task #1: Add time stamps to files
var taskOne = Task.Factory.StartNew(() => AddTimeStampsToFiles(fileList, progressDialogViewModel));
// Background Task #2: Resequence files
var taskTwo = taskOne.ContinueWith(t => this.ResequenceFiles(fileList, progressDialogViewModel));
// Announce that image processing is finished
var taskThree = taskTwo.ContinueWith(t => m_ViewModel.RaiseImageProcessingEndingEvent(), TaskScheduler.FromCurrentSynchronizationContext());
我接受了Fatty的答案,因为它确实提供了一个可行的替代方案。但是,我在我的应用程序中使用了这个答案中的方法,因为我使用的是TPL。那么,如何使任务连续运行呢?谢谢。@David Veeneman:我已经根据你的评论更新了我的答案。
// Background Task #1: Add time stamps to files
var taskOne = Task.Factory.StartNew(() => AddTimeStampsToFiles(fileList, progressDialogViewModel));
// Background Task #2: Resequence files
var taskTwo = taskOne.ContinueWith(t => this.ResequenceFiles(fileList, progressDialogViewModel));
// Announce that image processing is finished
var taskThree = taskTwo.ContinueWith(t => m_ViewModel.RaiseImageProcessingEndingEvent(), TaskScheduler.FromCurrentSynchronizationContext());