Programming in C# – Cancelling tasks

Pass a token to a cancellation task and it can be used to exit the task problematically

CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
      
CancellationToken token = cancellationTokenSource.Token;

Task task = Task.Run(() =>
{
    while(!token.IsCancellationRequested)
    {
          Console.Write(“*”);
          Thread.Sleep(1000);
    }
}, 
token);

It can be used in the asynchronous Task.

You can also add a continuation task that will run when the exit has been reached.

You can also use Task.WaitAny that takes a timeout value.

Leave a Reply

Your email address will not be published. Required fields are marked *