在服务器端Blazor中,如何取消页面或组件的long-运行后台任务?
In server-side Blazor, how to cancel a long-running background task of a page or component?
假设我有一个很长的 运行 任务,我已经初始化并从我页面 class 的 OnInitializedAsync() 方法开始,该方法派生自 Microsoft.AspNetCore.Components.ComponentBase。我用它来收集数据,它会不时更新 Ui,效果很好。
但在某些时候我需要摆脱那个后台任务。当客户更改到另一个页面或离开网络应用程序时,我想取消我的任务,这样它就不会永远保持 运行。我没有找到合适的生命周期方法。
有什么建议吗?
这是使用 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();
}
}
假设我有一个很长的 运行 任务,我已经初始化并从我页面 class 的 OnInitializedAsync() 方法开始,该方法派生自 Microsoft.AspNetCore.Components.ComponentBase。我用它来收集数据,它会不时更新 Ui,效果很好。
但在某些时候我需要摆脱那个后台任务。当客户更改到另一个页面或离开网络应用程序时,我想取消我的任务,这样它就不会永远保持 运行。我没有找到合适的生命周期方法。
有什么建议吗?
这是使用 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();
}
}