ASP.NET Core

Stopping EF Core queries when the client disconnects in ASP.NET Core

C# Corner Sophia Morales
ASP.NET Core

When a client closes the tab, ASP.NET Core ends the request but a query already running keeps holding database connections, CPU and pool capacity. The article shows how to carry the cancellation token from the controller through services and repositories into EF Core async calls, and how to keep cancellation out of the error logs.

Key points

  • A CancellationToken action parameter binds to the request token in controllers and Minimal APIs alike.
  • ToListAsync, FirstOrDefaultAsync, SaveChangesAsync, ExecuteUpdateAsync and ExecuteDeleteAsync all accept a cancellation token.
  • The token must be threaded through service and repository interfaces, or it never reaches the query.
  • Cancellation is cooperative: providers may not stop a command instantly, so keep command timeouts configured separately.
  • Catch OperationCanceledException with a token check before the general handler, or disconnects appear as failures.
  • For big result sets stream with AsAsyncEnumerable and WithCancellation, and never run parallel queries on one DbContext.

Real-world use

  • A report endpoint that scans thousands of rows and keeps the database busy after the user leaves the page
  • A mobile app that cancels in-flight order requests when connectivity changes
  • A frontend that cancels the previous search request as the user types new terms
  • Large dataset exports and CSV generation processed incrementally instead of loading everything into memory

This summary was generated by the agent from the original post on C# Corner. The full text and all rights belong to its author and publisher. Go to original

Report this story

Is something wrong with the summary, or do you own this content? Your message comes straight to my inbox.

Type of message

Related stories

Feedback

Found a bug or have an idea? Your message lands straight in my inbox.

Type of message