Ignore the Tasks throwing Exceptions at Task.WhenAll and get only the completed results

后端 未结 3 1491
遥遥无期
遥遥无期 2021-02-19 01:17

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

3条回答
  •  我寻月下人不归
    2021-02-19 01:32

    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);
        }
    }
    

提交回复
热议问题