Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Task.WhenAll handling Exceptions

I need help with a simple Task.WhenAll C# code. I have upto 50 different tasks being fired at the same time, however, some of these calls could return an error message.

I am trying to write the exception handling code, so that I can process the ones that worked (which it does), but capture the ones that errored, so I can perform additional code against them.

There is AggregateException, but is there a way to see which call/inputs that created that exception?

I'm unable to share the actual code due to strict company policy, but an example is as follows:

List<ListDetails> libs = getListDetails();
var tasks = new Task<List<ItemDetails>>[libs.Count];
for (int i = 0; i < libs.Count; i++)
{
    tasks[i] = getListItems(libs[i].ServerRelativeUrl, libs[i].ListId);
}

try
{
    await Task.WhenAll(tasks);
}
catch(AggregateException aex)
{
    //Capture which Server RelativeUrls and ListIDs that failed.    
}
like image 773
Cann0nF0dder Avatar asked Sep 04 '25 03:09

Cann0nF0dder


1 Answers

You can query the original tasks after waiting:

// Tasks taken from any source.
Task[] myTasks = ...;

// Logically wait ("await") for all tasks to complete,
// while ignoring possible exceptions (`Task.WhenAny` doesn't throw).
await Task.WhenAny(Task.WhenAll(myTasks));

// All tasks have completed - examine their outcome as you see fit.
foreach (var task in myTasks) {
 if (myTask.Status == RanToCompletion)
     ...
}

Please note that a previous version of this answer was incorrect. The core idea was sound, but the code contained a mistake.

like image 159
usr Avatar answered Sep 06 '25 01:09

usr