I have the following code which is firing off a number of async Task.
List<TimeoutException> TimeoutExceptions = new List<TimeoutException>();
List<TaskCanceledException> TaskCanceledExceptions = new List<TaskCanceledException>();
List<Exception> Exceptions = new List<Exception>();
List<AggregateException> AggregateExceptions = new List<AggregateException>();
List<Models.Channel.IChannel> channels = new List<Models.Channel.IChannel>();
channels.Add(new Models.Channel.DummyChannelName());
var tasks = new List<Task>();
foreach (Models.Channel.IChannel channel in channels)
{
try
{
var cts = new CancellationTokenSource();
cts.CancelAfter(channel.TimeOut);
tasks.Add(Task.Run(() =>
{
channel.Data = channel.RequestOffers(new Models.Request.AvailabilityRequest()).Result;
if (cts.Token.IsCancellationRequested)
cts.Token.ThrowIfCancellationRequested();
}, cts.Token));
}
catch (TimeoutException t)
{
TimeoutExceptions.Add(t);
}
catch (TaskCanceledException tc)
{
TaskCanceledExceptions.Add(tc);
}
catch (AggregateException ae)
{
AggregateExceptions.Add(ae);
}
catch(Exception ex)
{
Exceptions.Add(ex);
}
}
Task.WaitAll(tasks.ToArray(), TimeSpan.FromSeconds(5));
The problem I have is that if a task is cancelled because of a timeout I'm getting the following exception
<ExceptionMessage>One or more errors occurred.</ExceptionMessage>
<ExceptionType>System.AggregateException</ExceptionType>
Is it just a simple case that I need a Try Catch around Task.WaitAll, or should my code be structured differently.