ABP.io 应用停止时,我们可以使用 HostApplicationLifetime 对象的 CancellationToken 来取消后台任务。具体实现方式如下:
public override void ConfigureServices(ServiceConfigurationContext context)
{
...
context.Services.AddSingleton
using Microsoft.Extensions.Hosting;
public class HostApplicationLifetimeWrapper : IHostApplicationLifetime { private readonly IHostApplicationLifetime _lifetime;
public HostApplicationLifetimeWrapper(IHostApplicationLifetime lifetime)
{
_lifetime = lifetime;
}
public CancellationToken ApplicationStarted => _lifetime.ApplicationStarted;
public CancellationToken ApplicationStopping => _lifetime.ApplicationStopping;
public CancellationToken ApplicationStopped => _lifetime.ApplicationStopped;
public void StopApplication() => _lifetime.StopApplication();
}
public class BackgroundService : ITransientDependency { private readonly IHostApplicationLifetime _applicationLifetime;
public BackgroundService(IHostApplicationLifetime applicationLifetime)
{
_applicationLifetime = applicationLifetime;
}
public async Task DoWorkAsync(CancellationToken cancellationToken)
{
while (!cancellationToken.IsCancellationRequested)
{
...
}
// 应用停止时取消后台任务
_applicationLifetime.ApplicationStopping.Register(() =>
{
...
});
}
}
public async Task DoWorkAsync(CancellationToken cancellationToken) { while (!cancellationToken.IsCancellationRequested) { ... }
// 应用停止时取消后台任务
_applicationLifetime.ApplicationStopping.Register(() =>
{
cancellationTokenSource.Cancel();
});
}
以上就是 ABP.io 应用停止时取消后台任务的解决方法。