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