1

在下面的代码中,我有一个任务在用户按下任意键时被取消。这样做时,将调用 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);
}
4

0 回答 0