You have to pass the CancellationToken
to the Task, which will periodically monitors the token to see whether cancellation is requested.
// CancellationTokenSource provides the token and have authority to cancel the token
CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
CancellationToken token = cancellationTokenSource.Token;
// Task need to be cancelled with CancellationToken
Task task = Task.Run(async () => {
while(!token.IsCancellationRequested) {
Console.Write("*");
await Task.Delay(1000);
}
}, token);
Console.WriteLine("Press enter to stop the task");
Console.ReadLine();
cancellationTokenSource.Cancel();
In this case, the operation will end when cancellation is requested and the Task
will have a RanToCompletion
state. If you want to be acknowledged that your task has been cancelled, you have to use ThrowIfCancellationRequested
to throw an OperationCanceledException
exception.
Task task = Task.Run(async () =>
{
while (!token.IsCancellationRequested) {
Console.Write("*");
await Task.Delay(1000);
}
token.ThrowIfCancellationRequested();
}, token)
.ContinueWith(t =>
{
t.Exception?.Handle(e => true);
Console.WriteLine("You have canceled the task");
},TaskContinuationOptions.OnlyOnCanceled);
Console.WriteLine("Press enter to stop the task");
Console.ReadLine();
cancellationTokenSource.Cancel();
task.Wait();
Hope this helps to understand better.