0


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

应用场景:定时提醒。

标签: c# .net

本文转载自: https://blog.csdn.net/qq_21509637/article/details/130693349
版权归原作者 飘逸小强哥 所有, 如有侵权,请联系我们删除。

“NetCore下WebApi的后台服务BackgroundService”的评论:

还没有评论