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 : General, Web API

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.

Share with

Share on twitter
Share on facebook
Share on linkedin

Related FAQs

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

Please submit your question and answer.