.net core 如何在.net core 2.2中重新启动后台服务
我正在我的项目中创建一个BackgroundService,使用.net core 2.2 BackgroundService类, 我在尝试重新启动服务时遇到问题, 我注意到,当我调用“StartAsync”函数(在运行“StopAsync”函数之后)时,“ExcecuteAsync”函数(由StartAsync基函数)会被一个取消的令牌调用。 在看了后台服务课之后,我注意到 BackgroundService包含无法在任何位置重置的内部CancellationTokenSource 有没有办法重置或替换BackgroundService中的cancellationToken 示例代码:.net core 如何在.net core 2.2中重新启动后台服务,.net-core,background-service,.net-core-2.2,.net Core,Background Service,.net Core 2.2,我正在我的项目中创建一个BackgroundService,使用.net core 2.2 BackgroundService类, 我在尝试重新启动服务时遇到问题, 我注意到,当我调用“StartAsync”函数(在运行“StopAsync”函数之后)时,“ExcecuteAsync”函数(由StartAsync基函数)会被一个取消的令牌调用。 在看了后台服务课之后,我注意到 BackgroundService包含无法在任何位置重置的内部CancellationTokenSource 有没有办法
namespace Services.Background
{
[DisplayName("Device Structure Service")]
public class DeviceStructureService : BackgroundService
{
private readonly ILogger<DeviceStructureService> _logger;
public DeviceStructureService(ILogger<DeviceStructureService> logger)
{
_logger = logger;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
stoppingToken.Register(() => _logger?.LogDebug($"{serviceName} background task is stopping."));
while (!stoppingToken.IsCancellationRequested)
{
_logger?.LogInformation($"The {serviceName} running at: {DateTimeOffset.Now}");
try
{
await DoWork();
}
catch (Exception exception)
{
_logger?.LogCritical(exception.ToString());
}
await Task.Delay(1000, stoppingToken);
}
await StopAsync(stoppingToken);
}
public override Task StopAsync(CancellationToken cancellationToken)
{
_logger?.LogInformation($"The {serviceName} stopped at: {DateTime.Now}");
return base.StopAsync(cancellationToken);
}
public override Task StartAsync(CancellationToken cancellationToken)
{
_logger?.LogInformation($"The {serviceName} started at: {DateTime.Now}");
return base.StartAsync(cancellationToken);
}
}
}
命名空间服务。后台
{
[显示名称(“设备结构服务”)]
公共类设备结构服务:后台服务
{
专用只读ILogger\u记录器;
公用设备结构服务(ILogger记录器)
{
_记录器=记录器;
}
受保护的覆盖异步任务ExecuteAsync(CancellationToken stoppingToken)
{
stoppingToken.Register(()=>_logger?.LogDebug($“{serviceName}后台任务正在停止”);
同时(!stoppingToken.IsCancellationRequested)
{
_logger?.LogInformation($“运行于:{DateTimeOffset.Now}的{serviceName}”);
尝试
{
等待嫁妆();
}
捕获(异常)
{
_logger?.LogCritical(异常.ToString());
}
等待任务。延迟(1000,停止待命);
}
等待StopAsync(stoppingToken);
}
公共覆盖任务StopAsync(CancellationToken CancellationToken)
{
_logger?.LogInformation($“{serviceName}停止于:{DateTime.Now}”);
返回base.StopAsync(cancellationToken);
}
公共覆盖任务StartAsync(CancellationToken CancellationToken)
{
_logger?.LogInformation($“{serviceName}开始于:{DateTime.Now}”);
返回base.StartAsync(cancellationToken);
}
}
}
有没有办法重置或替换BackgroundService中的cancellationToken
没有
因为目标令牌源是基类中的private
和readonly
背景服务
由于
BackgroundService
源代码可用,因此没有任何东西可以阻止创建具有所需功能的本地版本,因为BackgroundService
源代码可用,没有任何东西可以阻止创建具有所需功能的本地版本。我正在尝试避免在我的代码中创建BackgroundService的本地版本。那么,对于目标令牌源,没有任何其他方法可以执行,因为它在基类中是私有且只读的。
private readonly CancellationTokenSource _stoppingCts = new CancellationTokenSource();