在下面的代码中,我有一个任务在用户按任意键时被取消。执行此操作时,将调用ContinuationTask,指出任务已取消。 ContinuationTask被配置为只在任务被取消时才运行 - 实际上它也是。
但是当我在调用线程中检查完成后任务的状态时,我会回来" RanToCompletion"。怎么可能?
以下是代码:
private static void ContinuationForCanceledTask()
{
CancellationTokenSource tokenSource = new CancellationTokenSource();
CancellationToken token = tokenSource.Token;
Task t = Task.Run(
() =>
{
while (!token.IsCancellationRequested)
{
Console.WriteLine("Nelson: Haha! - I am still running!!");
Thread.Sleep(1000);
}
token.ThrowIfCancellationRequested();
}, token);
//This continuation task is invoked as expected
t.ContinueWith(
(tawsk) =>
{
Console.WriteLine("Tawsk was canceled");
}
, TaskContinuationOptions.OnlyOnCanceled);
Console.WriteLine("Press any key to stop Nelson from laughing at you...");
Console.ReadKey();
tokenSource.Cancel();
t.Wait();
//Returns "RanToCompletion"
Console.WriteLine("State of the Task is {0}", t.Status);
}