Skip to content

Cooperative cancellation

Context: Cancellation in .NET is cooperative: the called code must periodically check the token and respond. It is not forced or immediate.

using System.Threading;
using System.Threading.Tasks;
public class LongRunningTask
{
public async Task RunAsync(CancellationToken token)
{
for (int i = 0; i < 1000000; i++)
{
if (token.IsCancellationRequested)
{
// Perform any cleanup
return;
}
await Task.Delay(1);
}
}
}
  • Check the token at logical points (loop start, after long operations).
  • Use ThrowIfCancellationRequested for simple cancellation.
  • Do not ignore cancellation requests.

File processing: Cancel reading a large file when the user aborts the operation.

Example: Cooperative cancellation sample