Skip to content

CancellationToken

Context: CancellationToken is passed to asynchronous methods to allow cancellation. The method can check IsCancellationRequested or call ThrowIfCancellationRequested().

using System.Threading;
using System.Threading.Tasks;
public class Processor
{
public async Task ProcessAsync(CancellationToken token)
{
for (int i = 0; i < 100; i++)
{
token.ThrowIfCancellationRequested();
await Task.Delay(100, token);
}
}
}

Use CancellationToken.None when you have no token to pass.

await processor.ProcessAsync(CancellationToken.None);

EF Core queries: ToListAsync(cancellationToken) accepts a token to cancel the database query.

Example: EF Core cancellation