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

标签 c# task-parallel-library

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

我可以重新 throw 吗? IE。我没有干扰任务 API 中的任何内容,对吧?

(我也会表达个人观点,即有序取消-清理-返回的要点似乎与异常作为它的载体不一致;我认为还有其他方法可以实现这一点——我会继续挖掘)

最佳答案

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

关于c# - 用户代码是否重新抛出 OperationCanceledException,从其自己的 try-catch 中捕获,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15445418/

相关文章:

c# - #Dotnet EF Core 迁移问题外键约束格式不正确

c# - 参数 5 : cannot convert from 'System.Drawing.Image' to 'string' - calling class1 from Main Class

c# - 重新抛出 AggregateException 的内部异常

c# - 为什么 main 不等到异步方法完成?

c# - 长时间停顿的并行任务

c# - TPL 如何正确取消任务

c# - byte[]转灰度BitmapImage

c# - 如何使用 Ajax.BeginForm 更新 div 并执行 javascript 函数?

c# - 异步等待、异常处理和继续使用 TaskContinuationOptions.OnlyOnFaulted

c# - 从 xml 文档解码 base64 编码的数据