キャンセルトークンのキャンセルリクエストを監視するための推奨される方法は、 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内で何も邪魔していませんね。
(私はまた、秩序だったキャンセル-クリーンアップ-リターンのポイントは、そのための手段を除いて対立しているように見えるという個人的な意見を表明します;それを達成する他の手段があると思います-私は掘り続けます)