The background long-running tasks are cancelled by using the CancellationToken object in Blazor. If an application downloads the data to render in view and then you navigate to another page, the CancellationToken cancels the download by using the cancel() method. Call the cancel() method by using the Dispose() method to cancel the background running task.
In the following example, the background running task in the FetchData.razor component is cancelled when a user navigates to other pages in Blazor.
[FetchData.razor]
@using System.Threading
@implements IDisposable
// . . .
@code {
private CancellationTokenSource cancellationToken = new CancellationTokenSource();
protected override async Task OnInitializedAsync()
{
forecasts = await Http.GetFromJsonAsync<WeatherForecast[]>("sample-data/weather.json", cancellationToken.Token);
}
public void Dispose()
{
cancellationToken?.Cancel();
cancellationToken?.Dispose();
}
// . . .
}
Refer to this documentation for more details.
Permalink