CancellationToken in Blazor: Stop Doing Work After the User Leaves
A user opens a page in your Blazor app, and a database query begins. Before the query finishes, they click away to another menu item. In many Blazor applications, that original database query just keeps running. The component is no longer visible, the result is no longer needed, and the user is three pages away—yet your server is still allocating memory, executing SQL, consuming connection pool slots, and awaiting HTTP requests. When the operation finally completes, it delivers results to a component instance that has already been disposed. This is precisely what CancellationToken is designed to solve. However, implementing cancellation in Blazor requires a clear distinction between disposable UI work and durable business operations . The Problem in Plain Code Consider a standard Blazor component reading from an EF Core service: Razor CSHTML @page "/customers" @inject CustomerService CustomerService <h1>Customers</h1> @if (customers is null) { <p>Loa...