觀察取消令牌消除請求的推薦方法似乎是ThrowIfCancellationRequested
。用戶代碼重新拋出OperationCanceledException,從其自己的try-catch中捕獲
但是,如果它被用戶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
}
}
上午我精再扔?即我不打擾Task API中的任何內容,是嗎? (我也會表達個人意見,有秩序的取消 - 清理 - 回報的觀點似乎與例外是它的載體不一致;我認爲還有其他方法可以實現這一點 - 我會繼續挖掘)
我這樣做,它似乎工作。有時候這就是你所需要的。 – theMayer 2013-03-17 04:27:48