[英]Continuation Task does not execute when Task is cancelled
這個想法 :創建一個Task
,打印越來越多的星號。 當用戶按下Enter
, Task
打印10個星號,然后停止。
代碼 :
namespace CancellingLongRunningTasks
{
using System;
using System.Threading;
using System.Threading.Tasks;
class Program
{
static void Main()
{
var cancellationTokenSource = new CancellationTokenSource();
var token = cancellationTokenSource.Token;
Task task = Task.Run(() =>
{
int count = 1;
while (!token.IsCancellationRequested)
{
Console.WriteLine(new string('*', count));
Thread.Sleep(1000);
count++;
}
}, token).ContinueWith(
parent =>
{
var count = 10;
while (count > 0)
{
Console.WriteLine(new string('*', count));
Thread.Sleep(1000);
count--;
}
}, TaskContinuationOptions.OnlyOnCanceled);
Console.WriteLine("Press enter to stop the task.");
if (Console.ReadLine().Contains(Environment.NewLine))
{
cancellationTokenSource.Cancel();
task.Wait();
}
}
}
}
問題 :為什么我的繼續任務沒有執行?
由於您沒有主動取消Task
,因此未執行該Task
,僅檢查是否請求取消。 使用CancellationToken.ThrowIfCancellationRequested
,它引發OperationCanceledException
並將Task
轉換為取消狀態,或者簡單地拋出帶有相應令牌的異常:
Task task = Task.Run(() =>
{
int count = 1;
while (!token.IsCancellationRequested)
{
Console.WriteLine(new string('*', count));
Thread.Sleep(1000);
count++;
}
token.ThrowIfCancellationRequested();
}, token)
等效於:
Task task = Task.Run(() =>
{
int count = 1;
while (!token.IsCancellationRequested)
{
Console.WriteLine(new string('*', count));
Thread.Sleep(1000);
count++;
}
throw new OperationCanceledException(token);
}, token)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.