用户代码是否重新抛出OperationCanceledException,从其自己的try-catch中捕获

时间:2013-03-16 04:02:23

标签: c# task-parallel-library

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

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

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

我好好重新投掷?即我没有打扰任务API中的任何内容,是吗?

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

1 个答案:

答案 0 :(得分:2)

rethrow应该没问题。但是不建议使用无参数捕获,因为它会吞下任何异常信息。您应该使用catch(Exception)并至少记录这些异常。