Guy Segal
Guy Segal

Reputation: 981

Task Cancellation

I want to wait until two tasks are done, but not in completed status. The wait should over when the tasks are both in cancellation status.

Does this line will continue when taskA and taskB will be canceld after activating cancellationToken?

Task.WaitAll(taskA, taskB); 

Thanks in advance.

Upvotes: 1

Views: 200

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1503290

Yes, WaitAll will exit when both tasks are in a terminal state, whatever that terminal state is.

However, it will complete by throwing an AggregateException if any of the tasks is faulted or cancelled. It will only complete normally (i.e. without an exception) if all of the tasks completed successfully. If you just want to keep going, you'll need to catch that exception. You can look at the InnerExceptions of the AggregateException to tell the difference between cancellation and faulting - or look at taskA and taskB themselves, of course.

From the documentation, in the exceptions part:

AggregateException At least one of the Task instances was canceled -or- an exception was thrown during the execution of at least one of the Task instances. If a task was canceled, the AggregateException contains an OperationCanceledException in its InnerExceptions collection.

Note that if you're using .NET 4.5 and async methods, you might want to use Task.WhenAll instead, which performs this waiting asynchronously - it returns a task which completes when the original tasks have completed.

Upvotes: 4

Related Questions