In the following asynchronous method, if both tasks fail, an exception will be unhandled. What is the correct way to handle exceptions from both tasks?
.NET interview question for Advanced practice.
Answer
Use Task.WhenAll wrapped in a single try-catch to await and handle exceptions from all tasks concurrently.
Explanation
The issue is that if task1 throws an exception, the await task1; line will throw, and the code will exit the method (or enter a catch block) without ever awaiting task2. If task2 also threw an exception, that exception would be lost and unobserved. The correct way to await multiple tasks concurrently and handle all their exceptions is to use Task.WhenAll. This creates a single task that completes when all of the provided tasks have completed. If any of the tasks fail, the WhenAll task also fails, and awaiting it will re-throw the exception from the first task that faulted (or an AggregateException if multiple tasks faulted).