Sobes.tech
Junior — Middle

How to deactivate or cancel a completed task in the system?

sobes.tech AI

Answer from AI

In C#, to deactivate or cancel a running task (Task), the cancellation mechanism via CancellationToken is usually used.

Main steps:

  1. Create a CancellationTokenSource, which provides a CancellationToken.
  2. Pass this token when starting the task.
  3. Inside the task, periodically check token.IsCancellationRequested and, if necessary, throw an OperationCanceledException or terminate the task.
  4. To cancel, call CancellationTokenSource.Cancel().

Example:

var cts = new CancellationTokenSource();
var token = cts.Token;

var task = Task.Run(() => {
    for (int i = 0; i < 100; i++)
    {
        if (token.IsCancellationRequested)
        {
            Console.WriteLine("Task canceled");
            token.ThrowIfCancellationRequested();
        }
        // Task work
        Thread.Sleep(100);
    }
}, token);

// To cancel the task
cts.Cancel();

try
{
    task.Wait();
}
catch (AggregateException ex) when (ex.InnerExceptions.Any(e => e is OperationCanceledException))
{
    Console.WriteLine("The task was canceled properly.");
}

Important: you should not forcibly stop a task; instead, support cancellation within the task itself.