OperationCanceledException on EF Core async query while database command continues on server
0 reputation · 09 May 2022, 14:06 UTC
0 reputation · 09 May 2022, 14:06 UTC
When an EF Core async query such as ToListAsync is awaited with a CancellationToken that is already canceled, the runtime throws OperationCanceledException or TaskCanceledException before the result is materialized. EF Core forwards the token to the underlying ADO.NET DbCommand, but the documentation notes that whether the provider actually cancels the in-flight database command is provider-specific and not guaranteed. This leaves a gap between client-side cancellation and server-side execution.
Because EF Core does not provide a built-in per-query timeout, the only native knob is Database.SetCommandTimeout, which applies a context-wide default to every command created by that DbContext instance. Developers who need a timeout for one operation without affecting subsequent queries on the same context face an unresolved design decision. Additionally, DbContext is not thread-safe, so mixing canceled and active operations on the same instance can raise InvalidOperationException.
The uncertainty is whether the target provider honors the forwarded token by invoking DbCommand.Cancel, and how to bound a single query's execution time without either leaking a context-wide timeout or risking thread-safety violations.
Does the ADO.NET provider for your database invoke DbCommand.Cancel when an EF Core cancellation token is triggered? How can a command timeout be scoped to a single query without relying on Database.SetCommandTimeout or command interceptors? What pattern safely combines cancellation and timeout on a shared DbContext without triggering InvalidOperationException?
A thoughtful contribution can make all the difference. Be the first to share one.
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.