简体   繁体   中英

Task WhenAll exception handling

I am looking to use Task.WhenAll in a situation where some tasks may fail, but I still need the result data from the rest of the completed tasks.

According to MSDN ,

If any of the supplied tasks completes in a faulted state, the returned task will also complete in a Faulted state, where its exceptions will contain the aggregation of the set of unwrapped exceptions from each of the supplied tasks.

However, what it doesn't say, is whether or not Task.WhenAll will still wait for the rest of the Tasks to complete in that instance. Can anyone provide any clarification on this issue?

As the documentation says:

Creates a task that will complete when all of the Task objects in an enumerable collection have completed.

So it will wait for all tasks to complete, regardless of whether any have thrown an exception already or been cancelled. Then it will aggregate the possible cancellations and exceptions and define its state. The results of the given tasks will be in the original tasks, as well as the exceptions and cancellations.

You can easily handle your requirement by wrapping the body of all the tasks in a try catch block and use a proper data structure as the result type of your task, so that you can understand if the task was failed or not.

An example could be useful to better understand what i am trying to tell you.

public async static void Main(string[] args)
{
   var task1 = GetIntegerAsync();
   var task2 = GetAnotherIntegerAsync();
   var result = await Task.WhenAll(new[] {task1, task2});

   foreach(var res in results)
   {
     // show a different message depending on res.isFailed
   }
}

private static async Task<(int result, bool isFailed)> GetIntegerAsync()
{
   try
   {
     await Task.Delay(1000).ConfigureAwait(false);
     return (10, false);
   }
   catch(Exception)
   {
     return (default(int), true);
   }
}

private static async Task<(int result, bool isFailed)> GetAnotherIntegerAsync()
{
   try
   {
     await Task.Delay(600).ConfigureAwait(false);
     throw new Exception("Something bad happened...");
   }
   catch(Exception)
   {
     return (default(int), true);
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM