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); } }}Best practices
Section titled “Best practices”- Check the token at logical points (loop start, after long operations).
- Use
ThrowIfCancellationRequestedfor simple cancellation. - Do not ignore cancellation requests.
Real-world usage example
Section titled “Real-world usage example”File processing: Cancel reading a large file when the user aborts the operation.
Example: Cooperative cancellation sample