[英]Why doesn't the status of a task change to canceled after cancel is called by CancellationTokenSource
我做了一個任務來計數,任務將在5秒后收到取消請求,但是在任務取消后,我檢查了任務的狀態。 任務狀態仍在運行。 為什么? 示例代碼如下:
var cts = new CancellationTokenSource();
cts.CancelAfter(5000);//Request Cancel after 5 seconds
var newTask = Task.Factory.StartNew(state =>
{
try
{
int i = 1;
var token = (System.Threading.CancellationToken)state;
while (true)
{
Console.WriteLine(i);
i++;
Thread.Sleep(1000);
token.ThrowIfCancellationRequested();
}
}
catch
{
}
finally
{
}
}, cts.Token, cts.Token);
try
{
newTask.Wait(10000, cts.Token);
}
catch
{
Console.WriteLine("Catch:"+ newTask.Status);//The status is Running
}
Console.ReadLine();
該代碼有兩個問題:
token.ThrowIfCancellationRequested()
確實token.ThrowIfCancellationRequested()
名稱所說,會引發異常。 由於您使用try/catch
塊來捕獲它,因此您最好從任務中返回。 “取消”之后的任務狀態不會Faulted
因為框架看不到異常。 Wait
。 這意味着5秒鍾后, Wait
將被取消,並且catch塊將被執行。 此時,任務可能會取消也可能不會取消。 您應該做的是擺脫任務主體中的try/catch/finally
,並從對Wait
的調用中刪除令牌: newTask.Wait(10000)
。
完整代碼:
var cts = new CancellationTokenSource();
cts.CancelAfter(5000);//Request Cancel after 5 seconds
var newTask = Task.Factory.StartNew(state =>
{
int i = 1;
var token = (System.Threading.CancellationToken)state;
while (true)
{
Console.WriteLine(i);
i++;
Thread.Sleep(1000);
token.ThrowIfCancellationRequested();
}
}, cts.Token, cts.Token);
try
{
newTask.Wait(10000);
}
catch
{
Console.WriteLine("Catch:"+ newTask.Status);
}
LINQpad輸出:
1
2
3
4
五
抓住:取消
嘗試將狀態打印到catch塊之外的控制台。 此時,您將打印狀態CancellationPended和Exception,但是在catch塊執行完成后,狀態立即更改。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.