Middle
How can a task be canceled in C#?
sobes.tech AI
Answer from AI
The mechanism of CancellationToken and CancellationTokenSource is used in C# to cancel task execution.
- A
CancellationTokenSourceis created. - A
CancellationTokenis obtained from theCancellationTokenSource. - The
CancellationTokenis passed to the method that performs the task. - Inside the executing method, the
IsCancellationRequestedproperty of the token is periodically checked. - If
IsCancellationRequestedistrue, anOperationCanceledExceptionis thrown or other termination logic is executed. - To request cancellation, the
Cancel()method is called on theCancellationTokenSourceobject.
Example usage:
using System;
using System.Threading;
using System.Threading.Tasks;
// Create a cancellation token source
CancellationTokenSource cts = new CancellationTokenSource();
CancellationToken token = cts.Token;
// Create a task
Task task = Task.Run(() =>
{
try
{
for (int i = 0; i < 100; i++)
{
// Check if cancellation is requested
if (token.IsCancellationRequested)
{
// Throw an OperationCanceledException
token.ThrowIfCancellationRequested();
}
// Simulate work
Console.WriteLine($"Working... {i}");
Thread.Sleep(100);
}
}
catch (OperationCanceledException)
{
// Handle cancellation exception
Console.WriteLine("Task canceled.");
}
catch (Exception ex)
{
// Handle other exceptions
Console.WriteLine($"An error occurred: {ex.Message}");
}
}, token); // Pass the token to the task
// Wait some time, then request cancellation
Thread.Sleep(500);
Console.WriteLine("Requesting cancellation...");
cts.Cancel();
// Wait for the task to complete
try
{
task.Wait();
}
catch (AggregateException ae)
{
// Handle exceptions, including OperationCanceledException
foreach (var e in ae.InnerExceptions)
{
if (e is OperationCanceledException)
{
Console.WriteLine("Canceled task completed (via Wait).");
}
else
{
// Handle other exceptions
Console.WriteLine($"Error during task completion: {e.Message}");
}
}
}
Console.WriteLine("Main program finished.");
Alternatives:
- Returning a special value or flag from the task.
- Checking an externally set flag without using
CancellationToken.
However, CancellationToken is the standard and recommended approach due to its integration with the Task Parallel Library (TPL), asynchronous operations, and support for OperationCanceledException.