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]
@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)
{
<p><em>Loading...</em></p>
}
else
{
<table class="table">
<thead>
<tr>
<th>Date</th>
<th>Temp. (C)</th>
<th>Temp. (F)</th>
<th>Summary</th>
</tr>
</thead>
<tbody>
@foreach (var forecast in forecasts)
{
<tr>
<td>@forecast.Date.ToShortDateString()</td>
<td>@forecast.TemperatureC</td>
<td>@forecast.TemperatureF</td>
<td>@forecast.Summary</td>
</tr>
}
</tbody>
</table>
}
@code {
private WeatherForecast[]? forecasts;
private readonly HttpClient httpClient = new HttpClient();
private CancellationTokenSource? cancellationToken;
protected override async Task OnInitializedAsync ()
{
cancellationToken = new CancellationTokenSource();
try
{
forecasts = await httpClient.GetFromJsonAsync<WeatherForecast[]>("sample-data/weather.json", cancellationToken.Token);
}
catch (OperationCanceledException)
{
// Task was cancelled
}
}
public void Dispose ()
{
cancellationToken?.Cancel();
cancellationToken?.Dispose();
}
}
Refer to this documentation for more details.
Share with