后台任务与定时任务的使用与差异

1.1、创建后台任务,需要继承BackgroundService,StartAsync可以不用实现,代码如下:

  public class TestWorker: BackgroundService
    {
        private readonly ILogger<TestWorker> _logger;

        public TestWorker(IServiceProvider services,
            ILogger<TestWorker> logger)
        {
            Services = services;
            _logger = logger;
        }

        public IServiceProvider Services { get; }

        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            _logger.LogInformation(
                "Consume Scoped Service Hosted Service running.");

            await DoWork(stoppingToken);
        }

        private async Task DoWork(CancellationToken stoppingToken)
        {
            Console.WriteLine("DoWork开始工作");

            int js = 0;
            while (!stoppingToken.IsCancellationRequested)
            {
                js++;
                Console.WriteLine($"计数执行器:{js}");
                await Task.Delay(1000, stoppingToken);
            }
        }

        //public override async Task StartAsync(CancellationToken cancellationToken)
        //{
        //    int js = 1000;
        //    while (!cancellationToken.IsCancellationRequested)
        //    {
        //        js++;
        //        Console.WriteLine($"计数执行器:{js}");
        //        await Task.Delay(1000,cancellationToken);
        //    }
        //}


        public override async Task StopAsync(CancellationToken stoppingToken)
        {
            _logger.LogInformation(
                "后台服务结束");

            await base.StopAsync(stoppingToken);
        }
    }

 1.2、调用方法 

builder.Services.AddHostedService<TestWorker>();

1.3、执行结果

 2.2、定时任务的创建,需要实现IHostedService, IDisposable两个接口,代码如下:

 public class TimedHostedService : IHostedService, IDisposable
    {
        private int executionCount = 0;
        private int executionCount2 = 0;
        private readonly ILogger<TimedHostedService> _logger;
        private Timer _timer = null!;
        private Timer _timer2=null!;

        public TimedHostedService(ILogger<TimedHostedService> logger)
        {
            _logger = logger;
        }

        public Task StartAsync(CancellationToken stoppingToken)
        {
            _logger.LogInformation("Timed Hosted Service running.");

            _timer = new Timer(DoWork, null, TimeSpan.Zero,
                TimeSpan.FromSeconds(1));

            _timer2 = new Timer(DoWork2, null, TimeSpan.Zero,
                TimeSpan.FromSeconds(10));

            return Task.CompletedTask;
        }

        private void DoWork(object? state)
        {
            var count = Interlocked.Increment(ref executionCount);
            Console.WriteLine($"1号后台计数器{count}");           
        }
        private void DoWork2(object? state)
        {
            var count = Interlocked.Increment(ref executionCount2);
            Console.WriteLine($"2号后台计数器{count}");
        }

        public Task StopAsync(CancellationToken stoppingToken)
        {
            _logger.LogInformation("Timed Hosted Service is stopping.");

            _timer?.Change(Timeout.Infinite, 0);
            _timer2?.Change(Timeout.Infinite, 0);
            return Task.CompletedTask;
        }

        public void Dispose()
        {
            _timer?.Dispose();
            _timer2.Dispose();
        }
    }

2.2、调用方法

builder.Services.AddHostedService<TimedHostedService>();

2.3、执行结果

应用场景说明

后台任务执行并不理解,因为会被阻塞,所以然另不需要阻塞的话,用定时后台任务比较合适;另外,后台任务被阻塞的情况是否有办法解决呢?

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值