我有以下代码触发了一些异步任务。
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));
我遇到的问题是,如果由于超时而取消任务,我会收到以下异常
<ExceptionMessage>One or more errors occurred.</ExceptionMessage>
<ExceptionType>System.AggregateException</ExceptionType>
这只是一个简单的案例,我需要一个围绕 Task.WaitAll 的 Try Catch,还是我的代码结构应该不同。