在服务器端Blazor中,如何取消长时间运行的页面或组件的后台任务? [英] In server-side Blazor, how to cancel a long-running background task of a page or component?

查看:180
本文介绍了在服务器端Blazor中,如何取消长时间运行的页面或组件的后台任务?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

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.

有什么建议吗?

推荐答案

以下是使用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();
    }
}

这篇关于在服务器端Blazor中,如何取消长时间运行的页面或组件的后台任务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆