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.
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With