简体   繁体   English

TaskContinuationOptions.OnlyOnFaulted与try catch

[英]TaskContinuationOptions.OnlyOnFaulted vs try catch

What's the difference between 之间有什么区别

var task3 = Task.Run(() => PerformLongTask()).ContinueWith(t => Log.Error(t.Exception), TaskContinuationOptions.OnlyOnFaulted);

and

var task3 = Task.Run(() => PerformLongTask());

private void PerformLongTask()
{
  try
  {
  //......
  }
  catch (Exception ex)
  {
     Log.Error(ex);
  }
}

I tried running both examples. 我尝试运行两个示例。 On the surface, they appear to behave the same. 从表面上看,它们的行为似乎相同。

Is one approach better than the other? 一种方法比另一种更好吗?

In this case, they're the same. 在这种情况下,它们是相同的。 However, if you don't own the innards of "PerformLongTask", you can't wrap its contents in a try-catch either. 但是,如果您没有“ PerformLongTask”的内在知识,则也不能将其内容包装在try-catch中。 Also, the task's Status will be set to RanToCompletion this way, even if it threw an exception. 此外,即使任务抛出异常,该任务的状态也将以这种方式设置为RanToCompletion。 If you have a continuation on the task, it will have to deal with the antecedent task potentially not having a valid Result. 如果您要继续执行该任务,则必须处理可能没有有效结果的先前任务。

I suppose the short of it is that in the former case, your exception handling logic is contained in a separate task, decoupled from the rest. 我想它的缺点是,在前一种情况下,您的异常处理逻辑包含在一个单独的任务中,与其余任务分离。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM