观察 cancelToken 取消请求的推荐方法似乎是 ThrowIfCancellationRequested
.
但是如果它被用户 try-catch 捕获会发生什么?从MSDN 的“如何:取消任务及其子项”中添加了 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 中的任何内容,是吗?
(我还将表达个人意见,有序取消-清理-返回的点似乎与例外是它的工具不一致;我认为还有其他方法可以实现这一点 - 我会继续挖掘)