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?
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;
}
}));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.