Say I have a long running task that I've initialized and started from the OnInitializedAsync() method of my page class which is derived from Microsoft.AspNetCore.Components.ComponentBase. I use it to collect data and it updates the Ui from time to time, which works quite fine.
But at some point I'll need to get rid of that background task. When the clients changes to another page or leaves the web app, I'd like to cancel my task so it wont keep on running for good. I don't find an appropriate lifecycle method.
Any suggestions?
Here is a sample to cancel a task using a CancellationTokenSource
@using System.Threading
@inject HttpClient _httpClient
@implement IDisposable
...
@code {
private CancellationTokenSource _cancellationTokenSource;
private IEnumerable<Data> _data;
protected override async Task OnInitializedAsync()
{
_cancellationTokenSource = new CancellationTokenSource();
var response = await _httpClient.GetAsync("api/data", _cancellationTokenSource.Token)
.ConfigureAwait(false);
response.EnsureSuccessStatusCode();
var content = await response.Content.ReadAsStringAsync()
.ConfigureAwait(false);
_data = JsonSerializer.Deserialize<IEnumerable<Data>>(content);
}
// cancel the task we the component is destroyed
void IDisposable.Dispose()
{
_cancellationTokenSource?.Cancel();
_cancellationTokenSource?.Dispose();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With