观察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中的任何内容,是吗?
(我也会表达个人观点,有条不紊地取消 - 清理 - 返回的点似乎与例外是它的载体不一致;我认为还有其他方法可以实现这一点 - 我会继续挖掘)
答案 0 :(得分:2)