shansfk shansfk - 1 month ago 6
C# Question

How to add a continuation for cancelled tasks

I have the following code

try
{
var cancellationTokenSource = new CancellationTokenSource();
var token = cancellationTokenSource.Token;

var task = Task.Run(() =>
{
while (token.IsCancellationRequested == false)
{
Console.Write("*");
Thread.Sleep(1000);
}
}, token).ContinueWith((t) =>
{
Console.WriteLine("You have canceled the task");
}, TaskContinuationOptions.OnlyOnCanceled);

Console.WriteLine("Press enter to stop the task");
Console.ReadLine();
cancellationTokenSource.Cancel();
task.Wait();
}
catch (AggregateException e)
{
Console.WriteLine($"Got an exception => {e.InnerExceptions[0].Message}");
}


In this when I cancel the task it always throws the error and the continuation task is not being executed.

But when I remove
TaskContinuationOptions.OnlyOnCanceled
from the continueWith parameter then the continuation task is being executed.

The book I am following has the code with the parameter
TaskContinuationOptions.OnlyOnCanceled
.

Is the behaviour correct or what is wrong here ?

I am new to threading. Please help me.

Answer

Your first task isn't actually being cancelled - you're observing that cancellation has been requested, but then you're letting the first task complete normally... which means your "only on cancellation" task is cancelled. If you change your code to:

while (token.IsCancellationRequested == false)
{
    Console.Write("*");
    Thread.Sleep(1000);
}
token.ThrowIfCancellationRequested();

... then it will behave as you expected.

Comments