Live Chat Icon For mobile
Live Chat Icon

How do I cancel background long-running tasks when a user navigates to another page in Blazor?

Platform: Blazor| Category : Web API, General

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.

@page "/fetchdata" 
<PageTitle>Weather forecast</PageTitle> 
@using BlazorServerApp.Data 
@using System.Threading 
@implements IDisposable 
@using System.Net.Http 
@inject WeatherForecastService ForecastService 

<h1>Weather forecast</h1> 
<p>This component demonstrates fetching data from a service.</p> 
@if (forecasts == null) 
    <table class="table"> 
                <th>Temp. (C)</th> 
                <th>Temp. (F)</th> 
            @foreach (var forecast in forecasts) 

@code { 
    private WeatherForecast[]? forecasts; 
    private readonly HttpClient httpClient = new HttpClient(); 
    private CancellationTokenSource? cancellationToken; 
    protected override async Task OnInitializedAsync () 
        cancellationToken = new CancellationTokenSource(); 
            forecasts = await httpClient.GetFromJsonAsync<WeatherForecast[]>("sample-data/weather.json", cancellationToken.Token); 
        catch (OperationCanceledException) 
            // Task was cancelled 

    public void Dispose () 

Refer to this documentation for more details.

Share with

Related FAQs

Couldn't find the FAQs you're looking for?

Please submit your question and answer.