When catching the Task.WhenAll AggregateException the TaskCancelledException is not available when other tasks are faulted. Running below code I get the following output:
TaskException
Caught in AggregateException
System.ArgumentOutOfRangeException
TaskCanceledException
Caught in TaskCanceledException
TaskException-TaskCanceledException
Caught in AggregateException
System.ArgumentOutOfRangeException
In the last test TaskCancelledException is not thrown, nor is it in the AggregateException.
Is there a means to also have the TaskCanceledException in the AggregateException, or do I always have to check the tasks exception when other tasks have errors?
using System;
using System.Threading;
using System.Threading.Tasks;
using System.Net.Http;
public static class Program
{
public static void Main()
{
var task1 = Task.FromException(new ArgumentOutOfRangeException());
var task2 = Task.FromCanceled(new CancellationToken(true));
Test("TaskException", new[] { task1 });
Test("TaskCanceledException", new[] { task2 });
Test("TaskException-TaskCanceledException", 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($"Caught in TaskCanceledException");
}
catch
{
Console.WriteLine($"Caught in AggregateException");
if (task.Exception is not null)
{
var t = task.Exception.Flatten();
foreach (var x in t.InnerExceptions)
{
Console.WriteLine(x.GetType());
}
}
}
}
}
}
httpTest.SendAsyncI would suggest to create explicitly a canceled task with eitherTask.FromException(new OperationCanceledException())orTask.FromCanceled(new CancellationToken(true)). It's not clear, just by reading the question, what kind of "canceled" thehttpTest.SendAsynctask is.Task.FromCanceled(new CancellationToken(true))? Have you tried that?httpTest.SendAsyncin your example with a task created with eitherTask.FromExceptionorTask.FromCanceled, and has similar behavior with thehttpTest.SendAsync. As it stands now, your example is imbalanced. On one hand we see theTask.FromException<int>(new ArgumentOutOfRangeException()), which is straightforward and clear. On the other hand we see thehttpTest.SendAsync, which is a mystery.