等待具有 OnlyOnFaulted Continuation 的任务会导致 AggregateException
我有一些简单的代码作为重现:
var taskTest = Task.Factory.StartNew(() =>
{
System.Threading.Thread.Sleep(5000);
}).ContinueWith((Task t) =>
{
Console.WriteLine("ERR");
}, TaskContinuationOptions.OnlyOnFaulted);
try
{
Task.WaitAll(taskTest);
}
catch (AggregateException ex)
{
foreach (var e in ex.InnerExceptions)
Console.WriteLine(e.Message + Environment.NewLine + e.StackTrace);
}
但是,我在 try catch 块中抛出了意外的 TaskCanceledException (它位于 AggregateException InnerExceptions 对象中)。 “任务被取消”。
为什么我会收到此异常?任务的延续永远不会触发,它没有生成任何异常,但在等待时我仍然得到聚合异常......
我希望有人能解释这对我来说有何意义:)
I have some simple code as a repro:
var taskTest = Task.Factory.StartNew(() =>
{
System.Threading.Thread.Sleep(5000);
}).ContinueWith((Task t) =>
{
Console.WriteLine("ERR");
}, TaskContinuationOptions.OnlyOnFaulted);
try
{
Task.WaitAll(taskTest);
}
catch (AggregateException ex)
{
foreach (var e in ex.InnerExceptions)
Console.WriteLine(e.Message + Environment.NewLine + e.StackTrace);
}
However, I'm getting an unexpected TaskCanceledException being thrown in the try catch block (it's in the AggregateException InnerExceptions object). "A task was canceled".
Why am I getting this exception? The Continuation for the task never fires, there was no exception generated by it, yet I still get the aggregate exception when waiting....
I'm hoping someone can explain how this makes sense to me :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您不是在等待带有 OnlyOnFaulted 延续的任务 - 您正在等待该延续(由
ContinueWith
返回)。延续永远不会触发,因为原始任务正常返回,所以它的行为就像被取消一样。对我来说很有意义。
我怀疑您想要创建任务,添加延续,然后等待原始任务:
You're not waiting on a task with an OnlyOnFaulted continuation - you're waiting on that continuation (returned by
ContinueWith
). The continuation is never going to fire because the original task returned normally, so it's acting as if it were cancelled.Makes sense to me.
I suspect you want to create the task, add the continuation, but then wait on the original task: