Okay, figure it out.
Move
token.ThrowIfCancellationRequested();
to a proper position.
Task task = Task.Run(() =>
{
while (!token.IsCancellationRequested)
{
Console.Write('*');
Thread.Sleep(1000);
}
}, token).ContinueWith((t)=>
{
t.Exception.Handle((e)=>true);
Console.WriteLine("You have canceled the task");
}, TaskContinuationOptions.OnlyOnCanceled);
token.ThrowIfCancellationRequested();
try
{
Console.WriteLine("Press enter to stop the task");
Console.ReadLine();
cancellationTokenSource.Cancel();
}
catch (AggregateException e)
{
Console.WriteLine(e.InnerExceptions[0].Message);
}
Console.WriteLine("Press enter to end the application");
Console.ReadLine();