newman911
newman911

Reputation: 303

Task.Factory.ContinueWhenAll with async continuationAction

What is the right way to link multiple asynchronous tasks together? I want to know that all tasks have succeeded, or that one task failed, and that my "pipeline" failed

Task task1 = RunTask1();
Task task2 = RunTask2();

Task task3_isDependentOnTasks1And2 = Task.Factory.ContinueWhenAll(
            new[] {task1,task2},
            async tasks => await RunTask3());

My experience debugging the code says that RunTask3 never gets awaited.

On the other hand this

Task task1 = RunTask1();
Task task2 = RunTask2();

Task task3_isDependentOnTasks1And2 = Task.Factory.ContinueWhenAll(
            new[] {task1,task2},
            tasks => RunTask3().GetAwaiter().GetResult());

Seems to work correctly.

Is the 2nd snippet the correct pattern?

Is there a better pattern to achieve my goal?

Upvotes: 0

Views: 142

Answers (1)

Stephen Cleary
Stephen Cleary

Reputation: 456417

Is there a better pattern to achieve my goal?

Yes. ContinueWhenAll is similar to ContinueWith; it's a low-level building block and I don't recommend using it. Use WhenAll instead:

Task task1 = RunTask1();
Task task2 = RunTask2();

await Task.WhenAll(task1, task2);
await RunTask3();

If you need the task instead of using await at this point in the code, a local async method will work fine:

Task task1 = RunTask1();
Task task2 = RunTask2();

Task task3_isDependentOnTasks1And2 = Run3When1And2AreDoneAsync();

async Task Run3When1And2AreDoneAsync()
{
  await Task.WhenAll(task1, task2);
  await RunTask3();
}

Upvotes: 3

Related Questions