捕获Task.WhenALl返回的Task的Exception

如果有一个任务抛出异常,则Task.WhenAll 会出错,并把这个异常放在返回的Task 中。
如果多个任务抛出异常,则这些异常都会放在返回的Task 中。但是,如果这个Task 在被await 调用,就只会抛出其中的一个异常。如果要得到每个异常,可以检查Task.WhenALl返回的Task 的Exception 属性:

        static async Task ThrowNotImplementedExceptionAsync()
        {
            throw new NotImplementedException();
        }
        static async Task ThrowInvalidOperationExceptionAsync()
        {
            throw new InvalidOperationException();
        }
        static async Task ObserveOneExceptionAsync()
        {
            var task1 = ThrowNotImplementedExceptionAsync();
            var task2 = ThrowInvalidOperationExceptionAsync();
            try
            {
                await Task.WhenAll(task1, task2);
            }
            catch (Exception ex)
            {
                // ex 要么是NotImplementedException,要么是InvalidOperationException

            }
        }

        static async Task ObserveAllExceptionsAsync()
        {
            var task1 = ThrowNotImplementedExceptionAsync();
            var task2 = ThrowInvalidOperationExceptionAsync();
            Task allTasks = Task.WhenAll(task1, task2);
            try
            {
                await allTasks;
            }
            catch
            {
                AggregateException allExceptions = allTasks.Exception;

            }
        }

使用Task.WhenAll 时,我一般不会检查所有的异常。通常情况下,只处理第一个错误就足够了,没必要处理全部错误。

原文地址:https://www.cnblogs.com/xbzhu/p/7356720.html