KarloX
KarloX

Reputation: 987

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?

Upvotes: 5

Views: 3404

Answers (1)

agua from mars
agua from mars

Reputation: 17404

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();
    }
}

Upvotes: 13

Related Questions