I am working on a Task parallel problem that I have many Tasks that may or may not throw Exception.
I want to process all the tasks that finishes properly and log the re
You can create a method like this to use instead of Task.WhenAll
:
public Task[]> WhenAllOrException(IEnumerable> tasks)
{
return Task.WhenAll(
tasks.Select(
task => task.ContinueWith(
t => t.IsFaulted
? new ResultOrException(t.Exception)
: new ResultOrException(t.Result))));
}
public class ResultOrException
{
public ResultOrException(T result)
{
IsSuccess = true;
Result = result;
}
public ResultOrException(Exception ex)
{
IsSuccess = false;
Exception = ex;
}
public bool IsSuccess { get; }
public T Result { get; }
public Exception Exception { get; }
}
Then you can check each result to see if it was successful or not.
EDIT: the code above doesn't handle cancellation; here's an alternative implementation:
public Task[]> WhenAllOrException(IEnumerable> tasks)
{
return Task.WhenAll(tasks.Select(task => WrapResultOrException(task)));
}
private async Task> WrapResultOrException(Task task)
{
try
{
var result = await task;
return new ResultOrException(result);
}
catch (Exception ex)
{
return new ResultOrException(ex);
}
}