【问题标题】:Is user code to rethrow an OperationCanceledException, caught from within its own try-catch用户代码是否重新抛出 OperationCanceledException,从它自己的 try-catch 中捕获
【发布时间】:2013-03-16 04:02:22
【问题描述】:

观察cancellationToken取消请求的推荐方法似乎是ThrowIfCancellationRequested

但是如果它被用户 try-catch 捕获会发生什么?来自MSDN's "How to: Cancel a Task and Its Children",添加了 try-catch 来说明问题:

snippet:

static void DoSomeWork(int taskNum, CancellationToken ct)
{
   try
   {
        for (int i = 0; i < maxIterations; i++)
        {
            // Do a bit of work. Not too much. 
            ...
            //ok not to do this check? most likely IsCancellationRequested does it already
            //if (ct.IsCancellationRequested)
            //{


                ct.ThrowIfCancellationRequested();


            //}
        }
    }
    catch(OperationCanceledException e1) // catching likely my own exception 
    {
       throw; // correct? anything else belongs here?
    }
    catch // ...
    {
        // do whatever else I might want to do here
    }
}

我可以重新投掷吗? IE。我不会打扰 Task API 中的任何东西,是吗?

(我还将表达个人意见,有序取消-清理-返回的点似乎与例外是它的载体不一致;我认为还有其他方法可以实现这一点 - 我会继续挖掘)

【问题讨论】:

  • 我这样做,它似乎工作。有时这就是你所需要的。

标签: c# task-parallel-library


【解决方案1】:

重新抛出应该没问题。但是不推荐使用无参数的 catch,因为它会吞下任何异常信息。您应该使用 catch (Exception) 并至少记录这些异常。

【讨论】:

  • 这与问题本身完全无关。
  • @Matz,使用不带参数的 catch 是一种非常糟糕的做法,有人可能会决定从问题中复制代码。
猜你喜欢
  • 2017-11-07
  • 1970-01-01
  • 1970-01-01
  • 2011-11-10
  • 1970-01-01
  • 2016-02-14
  • 2018-09-24
  • 2018-06-05
  • 2012-06-06
相关资源
最近更新 更多