NetCore下WebApi的后台服务BackgroundService

引言:最近发现个好东西就是BackgroundService,以前一直没注意到。个人理解它就是在你的后台开了一个子线程运行你的其他业务逻辑。


先上代码:

    public class ValueHisWorker : BackgroundService
    {
        public override async Task StartAsync(CancellationToken cancellationToken)
        {
            await base.StartAsync(cancellationToken);
        }

        public override Task StopAsync(CancellationToken cancellationToken)
        {
            return base.StopAsync(cancellationToken);
        }

        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            while (!stoppingToken.IsCancellationRequested)
            {
                try
                {
                    //业务逻辑
                    await Task.Delay(10000, stoppingToken);
                }
                catch (TaskCanceledException)
                {

                }
            }
        }  
    }

还需要在startup里面注册一下:

        public IServiceProvider ConfigureServices(IServiceCollection services)
        {           
            services.AddHostedService();
        }

应用场景:定时提醒。

你可能感兴趣的:(c#,.net)