如何检查所有任务是否已正确完成? [英] How to check that all tasks have been properly completed?

查看:87
本文介绍了如何检查所有任务是否已正确完成?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码中包含以下几行:

I have the following lines in my code:

    var taskA = Task.Factory.StartNew(WorkA);
    var taskB = Task.Factory.StartNew(WorkB);
    var allTasks = new[] { taskA, taskB };

    Task.Factory.ContinueWhenAll(allTasks, tasks => FinalWork(), TaskContinuationOptions.OnlyOnRanToCompletion);

但是当我运行它时,出现以下错误:

But when I run this, I get the following error:

为多个任务的延续而排除特定的延续类型是无效的.

It is invalid to exclude specific continuation kinds for continuations off of multiple tasks.

这是由选项 TaskContinuationOptions.OnlyOnRanToCompletion 引起的.

我的问题是如何检查所有任务是否正常完成工作(所有任务状态为 RanToCompletion ),然后执行 FinalWork()? 同时,应用程序执行其他任务.

My question is how to check that all tasks have done their work properly (all tasks statuses are RanToCompletion) and then do FinalWork()? In the meantime, the application performs other tasks.

推荐答案

基于@Peter Ritchie和@Ben McDougall的答案,我找到了一个解决方案.我通过删除冗余变量tasksTaskContinuationOptions.OnlyOnRanToCompletion

Based on @Peter Ritchie and @Ben McDougall answers I found a solution. I modified my code by removing redundant variable tasks and TaskContinuationOptions.OnlyOnRanToCompletion

var taskA = Task.Factory.StartNew(WorkA);
var taskB = Task.Factory.StartNew(WorkB);
var allTasks = new[] { taskA, taskB };
Task.Factory.ContinueWhenAll(allTasks, FinalWork);

FinalWork所在的位置:

private static void FinalWork(Task[] tasks)
{
   if (tasks.All(t => t.Status == TaskStatus.RanToCompletion))
   {
        // do "some work"
   }
}

如果所有tasks的状态为RanToCompletion,则将完成某些工作" .它会在所有任务完成后立即执行,并且不会阻止主要任务. 如果我至少取消一项任务,将什么也不会做.

If all tasks have status RanToCompletion, "some work" will be done. It will be performed immediately after all tasks have completed and will not block the main task. If I cancel at least one of the tasks, nothing will be done.

或者,您可以执行此操作,

Alternatively you can do this,

var taskA = Task.Factory.StartNew(WorkA);
var taskB = Task.Factory.StartNew(WorkB);
var allTasks = new[] { taskA, taskB };
var continuedTask = Task.WhenAll(allTasks).ContinueWith((antecedent) => { /*Do Work*/ }, TaskContinuationOptions.OnlyOnRanToCompletion));

这篇关于如何检查所有任务是否已正确完成?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆