Junior — Middle
How can CancellationToken be used to cancel asynchronous operations in your project?
sobes.tech AI
Answer from AI
CancellationToken in C# is used to cancel asynchronous operations, allowing the task to be properly interrupted upon request.
In a project, you can pass a CancellationToken to methods that support cancellation and check its status within asynchronous code. If the token signals cancellation, the operation should terminate early, releasing resources.
Example of usage:
public async Task LoadDataAsync(CancellationToken cancellationToken)
{
for (int i = 0; i < 10; i++)
{
cancellationToken.ThrowIfCancellationRequested();
await Task.Delay(1000); // simulate work
}
}
// Call with cancellation support
var cts = new CancellationTokenSource();
var task = LoadDataAsync(cts.Token);
// Cancel after 3 seconds
cts.CancelAfter(3000);
try
{
await task;
}
catch (OperationCanceledException)
{
Console.WriteLine("Operation was canceled");
}
This approach allows flexible management of asynchronous task execution time and improves application responsiveness.