Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In server-side Blazor, how to cancel a long-running background task of a page or component?

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?

like image 878
KarloX Avatar asked Jan 01 '23 11:01

KarloX


1 Answers

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();
    }
}
like image 107
agua from mars Avatar answered May 12 '23 04:05

agua from mars