Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check that all tasks have been properly completed?

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.

Which is caused by the option TaskContinuationOptions.OnlyOnRanToCompletion.

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.

like image 742
Zen Avatar asked Sep 03 '12 13:09

Zen


1 Answers

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);

Where FinalWork is:

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

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));
like image 174
2 revs, 2 users 82% Avatar answered Sep 20 '22 19:09

2 revs, 2 users 82%