等待具有OnlyOnFaulted Continuation的任务会导致AggregateException [英] Waiting on a Task with a OnlyOnFaulted Continuation causes an AggregateException

查看:178
本文介绍了等待具有OnlyOnFaulted Continuation的任务会导致AggregateException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些简单的代码作为副本:

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);
}

但是,我在try catch块(它在AggregateException InnerExceptions对象中)中引发了意外的TaskCanceledException. 任务已取消".

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".

为什么会出现此异常?任务的Continuation永远不会触发,它没有生成任何异常,但是在等待时我仍然会收到聚合异常.

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 :)

推荐答案

您不是在等待 具有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.

对我很有道理.

我怀疑您要创建任务,添加延续,然后等待原始任务:

I suspect you want to create the task, add the continuation, but then wait on the original task:

var taskTest = Task.Factory.StartNew(() =>
{
    System.Threading.Thread.Sleep(5000);

});
taskTest.ContinueWith((Task t) =>
{
    Console.WriteLine("ERR");
}, TaskContinuationOptions.OnlyOnFaulted);

这篇关于等待具有OnlyOnFaulted Continuation的任务会导致AggregateException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆