捕获 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());
}
}
}
}
}
}