当其他任务发生故障时,Task.WhenAll AggregateException 未捕获 TaskCancelledException\OperationCanceledException

问题描述 投票:0回答:0

捕获 WhenAll AggregateException 时,当其他任务出现故障时,TaskCancelledException 不可用。运行下面的代码我得到以下输出:

仅 HttpTimeout
任务取消异常

参数超出范围异常
System.ArgumentOutOfRangeException

HttpTimeout-ArgumentOutOfRangeException
System.ArgumentOutOfRangeException -> TaskCancelledException 不会抛出,也不在aggregateException 中

是否有办法在 AggregateException 中也包含 TaskCanceledException 或者当其他任务出现错误时我总是必须检查 httpclient 任务异常?

using System;
using System.Threading.Tasks;
using System.Net.Http;

public static class Program
{
    public static void Main()
    {
        var httpTest = new HttpClient() { BaseAddress = new Uri("http://www.google.com"), Timeout = TimeSpan.FromMilliseconds(1) };
        var task1 = httpTest.SendAsync(new HttpRequestMessage());
        var task2 = Task.FromException<int>(new ArgumentOutOfRangeException());
        Test("HttpTimeoutOnly", new[] { task1 });
        Test("ArgumentOutOfRangeException", new[] { task2 });
        Test("HttpTimeout-ArgumentOutOfRangeException", new Task[] { task1, task2 });

        static async void Test(string title, Task[] tasks)
        {
            Console.WriteLine();
            Console.WriteLine(title);
            var task = Task.WhenAll(tasks);
            try { await task; }            
            catch (TaskCanceledException)
            {
                Console.WriteLine($"TaskCanceledException");
            }
            catch
            {
                if(task.Exception is not null)
                {
                    var t = task.Exception.Flatten();
                    foreach(var x in t.InnerExceptions)
                    {
                        Console.WriteLine(x.GetType());
                    }                   
                }
            }
        }        
    }
}
c# task dotnet-httpclient
© www.soinside.com 2019 - 2024. All rights reserved.