1

I am using Using async/await for multiple tasks as reference.

public async Task DoWork() {

    int[] ids = new[] { 1, 2, 3, 4, 5 };
    await Task.WhenAll(ids.Select(i => DoSomething(1, i, blogClient)));
}

Is it possible to catch an exception on the specific index. As in, when DoSomething throws an exception on i, I can catch that specific index?

Jimbo
  • 13
  • 2
  • If there isn't, you can have your individual DoSomething functions throw an exception with the index as part of the data, then catch it at the DoWork level – Prodigle Feb 13 '19 at 15:33
  • Possible duplicate of [Task WhenAll exception handling](https://stackoverflow.com/questions/52675789/task-whenall-exception-handling) – demo Feb 13 '19 at 15:34

1 Answers1

0

A simple approach is to catch the Exception, insert the index information on the exception's Data, and rethrow :

int[] ids = new[] {1, 2, 3, 4, 5};
await Task.WhenAll(ids.Select(i =>
{
    try
    {
        return DoSomething(1, i, null);
    }

    catch (Exception ex)
    {
        ex.Data["FailedIndex"] = i; // Information about failed index
        throw;
    }
}));
Perfect28
  • 11,089
  • 3
  • 25
  • 45