I’m running a method for a list of inputs; this list is provided by the user. If an exception happens in processing one input, I have to remove that from the output table. The code looks something like this:
List<Task> methodsList = new List<Task>();
for (int i = 0; i < inputList.Count; i++)
{
int arg = i;
Task newTask = Task.Factory.StartNew(() => ProcessInput(i));
methodsList.Add(newTask);
}
if (methodsList.Count != 0)
{
try
{
Task.WaitAll(methodsList.ToArray());
}
catch (AggregateException ex)
{
foreach (Exception innerEx in ex.InnerExceptions)
{
throw innerEx;
}
}
}
The problem is that when I wait for all the tasks to finish, the AggregatedException does not give me any information about which thread was failed. I was thinking about handling this by creating a collection and adding the index of finished processes to that list and checking it at the end to see which inputs where not processed, but I was wondering if there is an easier way of doing it.
Yes there’s an easier way, handle the exception in the task itself. Trying to handle it when all the state is gone is next to impossible. Handling it in the task is still a formidable job but at least you’ll have a much better idea what went wrong where.