【用.NET5写Windows服务】四、托管服务和监听任务

默认创建的托管服务是一个1秒轮询的任务,而windows服务的很多应用场景需要一直监听的任务,此篇我们就改造一下默认创建的托管服务,使其能够一直监听。

改造Worker.cs

重写BackgroundService.StartAsyncBackgroundService.StopAsyncBackgroundService.ExecuteAsync方法

public class Worker : BackgroundService
{
    
    
    private readonly ILogger<Worker> _logger;
    private readonly IConfiguration _configuration;

    public HostedServiceOptions HostedServiceOptions {
    
     get; private set; }

    public Worker(ILogger<Worker> logger, IConfiguration configuration)
    {
    
    
        _logger = logger;
        _configuration = configuration; //依赖注入IConfiguration
    }

    public override async Task StartAsync(CancellationToken cancellationToken)
    {
    
    
        _logger.LogInformation("Worker starting at: {time}", DateTimeOffset.Now);

        HostedServiceOptions = _configuration.GetSection(HostedServiceOptions.HostedService).Get<HostedServiceOptions>(); //绑定并返回指定的类型

        await base.StopAsync(cancellationToken);
    }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
    
    
        await Task.Run(async () =>
        {
    
    
            //++如果服务被停止,那么下面的IsCancellationRequested会返回true,我们就应该结束循环
            while (!stoppingToken.IsCancellationRequested)
            {
    
    
                _logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
                await Task.Delay(HostedServiceOptions.WorkerInterval, stoppingToken); //设置托管任务轮询时间
            }
        }, stoppingToken);
    }

    public override async Task StopAsync(CancellationToken cancellationToken)
    {
    
    
        _logger.LogInformation("Worker stopping at: {time}", DateTimeOffset.Now);

        await base.StopAsync(cancellationToken);
    }
}

猜你喜欢

转载自blog.csdn.net/danding_ge/article/details/112006139