I am trying to cancel a Task<> by calling the CancellationTokenSource.Cancel() method within the task, but I cannot get it to work.
Here is the code I am using:
TaskScheduler ts = TaskScheduler.Current;
CancellationTokenSource cts = new CancellationTokenSource();
Task t = new Task( () =>
{
Console.WriteLine( "In Task" );
cts.Cancel();
}, cts.Token );
Task c1 = t.ContinueWith( antecedent =>
{
Console.WriteLine( "In ContinueWith 1" );
}, CancellationToken.None, TaskContinuationOptions.OnlyOnRanToCompletion, ts );
Task c2 = c1.ContinueWith( antecedent =>
{
Console.WriteLine( "In ContinueWith 2" );
}, TaskContinuationOptions.NotOnCanceled );
t.Start();
Console.ReadKey();
Environment.Exit( 1 );
This print outs:
In Task
In ContinueWith 1
In ContinueWith 2
What I expected was this:
In Task
Am I missing something here? Can tasks only be cancelled outside of the task?