【发布时间】:2015-01-26 12:46:04
【问题描述】:
如何将任务中引发的异常标记为已处理。问题是当我调用任务的Wait() 方法时,即使我很久以前已经处理了AggregateException,它也会抛出AggregateException。
以下代码 sn -p 显示了我要解决的问题。在我的原始代码中,我在代码的一部分中处理AggregateException,并在代码的另一部分中调用Wait() 方法。但问题是一样的。
static void Main(string[] args)
{
Task task = null;
try
{
task = new Task(() =>
{
Console.WriteLine("Task started");
Thread.Sleep(1000);
throw new InvalidOperationException("my test exception");
});
task.ContinueWith(t =>
{
Console.WriteLine("Task faulted");
AggregateException ae = t.Exception;
ae.Flatten().Handle(ex =>
{
if (typeof(InvalidOperationException) == ex.GetType())
{
Console.WriteLine("InvalidOperationException handled --> " + ex.Message);
return true;
}
return false;
});
}, TaskContinuationOptions.OnlyOnFaulted);
task.Start();
Thread.Sleep(2000);
task.Wait();
}
catch (AggregateException ae)
{
Console.WriteLine("AggregateException thrown again!!! Why???");
ae.Flatten().Handle(ex =>
{
Console.WriteLine(ex.Message);
return true;
});
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.WriteLine("Finished");
Console.Read();
}
上面的代码产生以下输出:
- 任务已启动
- 任务出错
- InvalidOperationException 已处理 --> 我的测试异常
- AggregateException 再次抛出!!!为什么???
- 我的测试异常
- 完成
【问题讨论】:
-
似乎没有办法将异常标记为已处理。如果任务状态出错,调用 wait 方法总是会抛出 AggregateException。
标签: c# .net exception-handling task-parallel-library aggregateexception