在服务器端Blazor中,如何取消长时间运行的页面或组件的后台任务?

问题描述 投票:1回答:1

说我有一个长期运行的任务,该任务已经从我的页面类的OnInitializedAsync()方法初始化并开始,该方法从Microsoft.AspNetCore.Components.ComponentBase派生。我用它来收集数据,它会不时更新Ui,效果很好。

但是在某些时候,我需要摆脱该后台任务。当客户端切换到另一个页面或离开Web应用程序时,我想取消任务,这样它就不会一直运行下去。我找不到合适的生命周期方法。

有什么建议吗?

blazor blazor-server-side
1个回答
0
投票

这里是使用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();
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.