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:
- Create a
CancellationTokenSource, which provides aCancellationToken. - Pass this token when starting the task.
- Inside the task, periodically check
token.IsCancellationRequestedand, if necessary, throw anOperationCanceledExceptionor terminate the task. - 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.