如何在.net core 2.2中重新启动后台服务

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

[我正在使用.net core 2.2 BackgroundService类在我的项目中创建BackgroundService,我在尝试重新启动服务时遇到问题,我注意到,当我调用“ StartAsync”函数(运行“ StopAsync”函数后)时,“ ExcecuteAsync”函数被StartAsync基本函数调用了,并且令牌被取消了。看完BackgroundService类后,我注意到BackgroundService包含一个内部CancellationTokenSource,我无法在任何地方进行重置。 BackgroundService source

是否有方法可以重置或替换BackgroundService内部的cancellicToken?

示例代码:

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);
        }

    }
}
.net-core background-service .net-core-2.2
1个回答
0
投票

是否有方法可以重置或替换BackgroundService内部的cancellicToken?

因为目标令牌源是基类中的privatereadonly

BackgroundService

private readonly CancellationTokenSource _stoppingCts = new CancellationTokenSource();

由于BackgroundService源代码可用,因此没有任何事情可以阻止创建具有所需功能的本地版本

© www.soinside.com 2019 - 2024. All rights reserved.