Task.WhenAll遇异常是否等待所有任务?多任务抛异常后其他任务是否完成?
Great questions about Task.WhenAll behavior—let's break this down clearly.
Question 1: Does Task.WhenAll wait for all tasks to complete if one throws an exception?
Short answer: Yes, it does.
Task.WhenAll doesn't bail out the moment a task faults. It will wait until every task in the collection has finished running—whether that's successfully completing, throwing an exception, or being canceled. Only after all tasks are done will it complete itself, and if any tasks failed, it will throw an AggregateException that wraps all the exceptions from the failed tasks.
Question 2: If one task throws an exception when using Task.WhenAll, does the other task keep running until completion?
Absolutely.
Once you start a Task, it runs independently unless you explicitly cancel it via a CancellationToken. Task.WhenAll doesn't interfere with the execution of the tasks you pass to it—its only job is to wait for all of them to finish and aggregate their results (or exceptions). So even if one task throws early, the other will keep going until it's done with its work.
Let me throw in a quick code example to demonstrate both behaviors:
using System; using System.Threading.Tasks; class Program { static async Task Main() { try { var task1 = Task.Run(async () => { Console.WriteLine("Task 1 starting..."); await Task.Delay(2000); throw new InvalidOperationException("Task 1 failed!"); }); var task2 = Task.Run(async () => { Console.WriteLine("Task 2 starting..."); await Task.Delay(3000); Console.WriteLine("Task 2 completed successfully!"); }); await Task.WhenAll(task1, task2); } catch (AggregateException ex) { foreach (var innerEx in ex.InnerExceptions) { Console.WriteLine($"Caught exception: {innerEx.Message}"); } } } }
If you run this, you'll see:
- Both tasks start right away
- Task 1 throws after 2 seconds, but Task 2 keeps running for another second until it finishes
- Only after Task 2 completes does
Task.WhenAllcomplete, and theAggregateExceptionis caught
This confirms that all tasks run to completion, and WhenAll waits for all of them before reporting errors.
内容的提问来源于stack exchange,提问作者Jonatan Dragon

