Task.WaitAll how to find tasks that cause an AggregateException

Say I got the following code:

var tasks = BuildTaskList(); try { Task.WaitAll(tasks.ToArray()); } catch (AggregateException exception) { } 

How do I know which task selected which of the exceptions in exception.InnerExceptions ?

+4
source share
3 answers

You still have a Tasks list, and each Task has an Exception property. Using this, you can find out which exceptions belong to Task .

But, if possible, it would be better to use Task.WhenAll or TaskFactory.ContinueWhenAll than block Wait.

+7
source
 var throwers = tasks.Where(task => task.Exception != null); 
+2
source
  var t1 = Task.Factory.StartNew(() => Console.WriteLine("Task 1")); var t2 = Task.Factory.StartNew(() => Console.WriteLine("Task 2")); var t3 = Task.Factory.StartNew(() => { throw new InvalidOperationException(); }); var t4 = Task.Factory.StartNew(() => Console.WriteLine("Task 4")); Task.Factory.ContinueWhenAll(new[] { t1, t2, t3, t4 }, tasks => { foreach (var t in tasks) { if (t.Status == TaskStatus.Faulted) { // this will run for t3 Console.WriteLine("This task has been faulted."); } } }); 
0
source

Source: https://habr.com/ru/post/1497788/


All Articles