观察cancelToken取消请求的推荐方法似乎是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
}
}
我好好重新投掷?即我没有打扰任务API内部的任何内容,是吗?
(我也会表达个人观点,有条不紊地取消 – 清理 – 返回的点似乎与例外是它的载体不一致;我认为还有其他方法可以实现这一点 – 我会继续挖掘)
最佳答案 重新抛出应该没问题.但是不建议使用无参数捕获,因为它会吞下任何异常信息.您应该使用catch(Exception)并至少记录这些异常.