Task 中的异常 属性 什么时候可以有值?

when the exception property in the Task can have a value?

想知道"continueWhith"什么时候有异常

我做了一个这样的代码。

Task.Factory.StartNew(() =>
{
   if(HasException())
       throw new Exception("Exception");
   // Logic
}).ContinueWith(x =>
{
   // Do something to UI.
}, CancellationToken.None, TaskContinuationOptions.NotOnFaulted, 
_uiScheduler).continueWith(x =>
{
   if (x.Exception.IsNotNull()) // Exception handling here.
     ShowExceptionMessage(x.Exception);            
}

本以为任务最后continueWith会出现异常,结果并没有。

Task最后continueWith是不是没有异常?

我想知道如何在 continueWith 中设置异常 属性。

谢谢。

Is it right that there isn't an Exception in the Task at last continueWith?

是的,因为它是您 "Do something to UI" 任务的延续。如果第二个任务失败,x.Exception 中只会出现异常。

事实上,我不希望您达到 任一个 延续,因为您的第一个任务总是出错,并且第一个延续明确表示只有在 [=21] 时才执行=]没有错误。

备选方案:

  • 通过第二个任务的结果传播异常(如果有)
  • 将两个延续添加到原始任务中,而不是将它们链接起来。 (这可能是您最初的意图,以便将故障路径和未故障路径分开。在这种情况下,将两个延续附加到第一个任务,并使用 TaskContinuationOptions.OnlyOnFaulted 作为第二个延续 - 那么您就不需要完全需要异常检查。)
  • 在原始任务中保留一个局部变量,这样您就可以从第二个延续中得到它

理想情况下,我建议使用 async/await 而不是所有继续传递。它往往会使事情变得更简单。