2 ways to handle exception with c#’s Task.WhenAll

Aman Singh Parihar
2 min readDec 19, 2023

--

Exception handling in asynchronous is bit of a tedious job. Here, we will look 2 ways to handle it properly.

Photo by Beth Macdonald on Unsplash
  • 1st way to handle exception.
var tasks = new List<Task>();

Func<Task> function1 = async () =>
{
await Task.Delay(2000); // To show some long running tasks
throw new Exception(message: "Task Exception1");
};

Func<Task> function2 = async () =>
{
await Task.Delay(2000); // To show some long running tasks
throw new IndexOutOfRangeException(message: "Task Exception2");
};

var oneTask = await Task.Factory.StartNew(function1);
var TwoTask = await Task.Factory.StartNew(function2);

tasks.Add(oneTask);
tasks.Add(TwoTask);

try
{
await Task.WhenAll(tasks);
}
catch (Exception ex)
{
Console.WriteLine(ex);
}

When we run the above, we get exception message as Task Exception1, we didn’t get Task Exception2, as await will unwrap the first exception and return it. It means we are not getting the details of each of our failed tasks.

  • 2nd way to handle exception

Here, we have captured the task returned from the WhenAll and awaited on it.

var tasks = new List<Task>();

Func<Task> function1 = async () =>
{
await Task.Delay(2000); // To show some long running tasks.
throw new Exception(message: "Task Exception1");
};

Func<Task> function2 = async () =>
{
await Task.Delay(2000); // To show some long running tasks.
throw new IndexOutOfRangeException(message: "Task Exception2");
};

var oneTask = await Task.Factory.StartNew(function1);
var TwoTask = await Task.Factory.StartNew(function2);

tasks.Add(oneTask);
tasks.Add(TwoTask);
Task allTasks = null; // To capture the task returned from WhenAll method
try
{
allTasks = Task.WhenAll(tasks);
await allTasks; // awaiting the task here
}
catch (Exception ex)
{
// Capturing all the exceptions from the task
AggregateException exception = allTasks.Exception;
foreach (var error in exception.InnerExceptions)
{
Console.WriteLine(error);
}
Console.WriteLine(ex);
}

When we run the above code, we are able to get the exceptions returned from both of our method.

--

--

Aman Singh Parihar
Aman Singh Parihar

Written by Aman Singh Parihar

I work as a software engineer and having experience in web technologies. I like to share my knowledge with the community and aspire to learn cool things.

No responses yet