In the following piece of code I have a task that gets canceled when the user presses any key. When doing so the ContinuationTask is invoked stating that the task was canceled. The ContinuationTask is configured so that it only runs when a task was canceled - and it actually does.
But when I check for the status of the task after completion in the calling thread, I get back "RanToCompletion". How is that possible?
Here is the code:
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);
}