Entity Framework Core Interview Question #186
How should cancellation tokens be used with EF Core?
Testing, Production Practices & Senior Real-World Scenarios Senior Advanced
Quick Interview Answer
Pass the request or operation CancellationToken to asynchronous EF Core methods such as ToListAsync and SaveChangesAsync. Cancellation allows abandoned HTTP requests, shutdown operations, or timed-out workflows to stop waiting for database work when the provider supports cancellation. Cancellation is not a substitute for efficient queries or appropriate command timeouts.
Detailed Explanation
Pass the request or operation CancellationToken to asynchronous EF Core methods such as ToListAsync and SaveChangesAsync. Cancellation allows abandoned HTTP requests, shutdown operations, or timed-out workflows to stop waiting for database work when the provider supports cancellation. Cancellation is not a substitute for efficient queries or appropriate command timeouts.
Code Example
var items = await db.Products
.AsNoTracking()
.ToListAsync(cancellationToken);
await db.SaveChangesAsync(cancellationToken);