ASP.NET Core 2.2 基础知识(九) 运用托管效劳完成后台


玖富娱乐是一家为代理招商,直属主管信息发布为主的资讯网站,同时也兼顾玖富娱乐代理注册登录地址。

在 ASP.NET Core 中,后台义务作为托管效劳完成.托管效劳是一个类,并且必需完成 IHostedService 接口,该接口界说了两个要领:

  • StartAsync(CancellationToken cancellationToken)  该要领包罗启动后台义务的逻辑,当启动效劳器并触发 IApplicationLifetime.ApplicationStarted 后挪用该要领.
  • StopAsync(CancellationToken cancellationToken)主机一般封闭时触发,包罗完毕后台义务和措置惩罚任何非托管资本的逻辑.若是运用不测封闭,则可能不会挪用.

托管效劳在运用启动时激活一次,在运用封闭时一般封闭.完成 IDisposable 时,可在措置效劳容器时措置惩罚资本.若是在实行后台义务时期激发毛病,纵然未挪用 StopAsync ,也应挪用 Dispose.

示例一:计时的后台义务

    public class TimedHostedService : IHostedService, IDisposable
    {

        private readonly ILogger _logger;
        private Timer _timer;
        public TimedHostedService(ILogger<TimedHostedService> logger)
        {
            _logger = logger;
        }

        public Task StartAsync(CancellationToken cancellationToken)
        {
            _logger.LogInformation("Timed Background Service is starting."   DateTime.Now);
            _timer = new Timer(DoWork, null, TimeSpan.Zero, TimeSpan.FromSeconds(5));//马上实行一次,每5秒实行一次
            return Task.CompletedTask;
        }


        private void DoWork(object state)
        {
            _logger.LogInformation("Timed Background Service is working."   DateTime.Now);
        }

        public Task StopAsync(CancellationToken cancellationToken)
        {
            _logger.LogInformation("Timed Background Service is stopping."   DateTime.Now);
            _timer?.Change(Timeout.Infinite, 0);//不再实行
            return Task.CompletedTask;
        }


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

 

注册该后台义务:

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
            services.AddHostedService<TimedHostedService>();
        }

 

在控制台启动该项目,时期用 ctrl C 完毕运用.

实在官方帮我们封装了一个类来简化上述代码:

  /// <summary>
  /// Base class for implementing a long running <see cref="T:Microsoft.Extensions.Hosting.IHostedService" />.
  /// </summary>
  public abstract class BackgroundService : IHostedService, IDisposable

 

因而上述代码能够修改成:

    public class MyBackGroundTask : BackgroundService
    {
        private readonly ILogger _logger;

        private Timer _timer;

        public MyBackGroundTask(ILogger<MyBackGroundTask> logger)
        {
            _logger = logger;
        }
        
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            _logger.LogInformation($" MyBackGroundTask is starting. {DateTime.Now}");
            while (!stoppingToken.IsCancellationRequested)
            {
                _logger.LogInformation($" MyBackGroundTask is working. {DateTime.Now}");
                await Task.Delay(5000, stoppingToken);
            }
            _logger.LogInformation($" MyBackGroundTask is stopping. {DateTime.Now}");
        }
    }

 

然则,我发明 

_logger.LogInformation($" MyBackGroundTask is stopping. {DateTime.Now}");

这句代码一直不实行.不知道是那里没搞对.愿望大神能帮个忙..

 

-玖富娱乐是一家为代理招商,直属主管信息发布为主的资讯网站,同时也兼顾玖富娱乐代理注册登录地址。-

 示例二:在后台义务中运用有作用域的效劳

要运用有作用域的效劳,须要先建立一个作用域.默许情况下,不会为托管效劳建立作用域.

 

    public interface IScopedProcessingService
    {
        void DoWork();
    }

    public class ScopedProcessingService : IScopedProcessingService
    {
        private readonly ILogger _logger;
        public ScopedProcessingService(ILogger<ScopedProcessingService> logger)
        {
            _logger = logger;
        }
        public void DoWork()
        {
            _logger.LogInformation($"Scoped Processing Service is working. {DateTime.Now}");
        }
    }

 

    public class ConsumeScopedServiceHostedService : IHostedService
    {

        private readonly ILogger _logger;

        public IServiceProvider Services { get; }

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

        public Task StartAsync(CancellationToken cancellationToken)
        {
            _logger.LogInformation($"Consume Scoped Service Hosted Service is starting. {DateTime.Now}");
            DoWork();
            return Task.CompletedTask;
        }

        private void DoWork()
        {
            _logger.LogInformation($"Consume Scoped Service Hosted Service is working. {DateTime.Now}");
            using (IServiceScope scope = Services.CreateScope())//建立一个作用域.
            {
                IScopedProcessingService scopedProcessingService = scope.ServiceProvider.GetRequiredService<IScopedProcessingService>(); scopedProcessingService.DoWork(); }
        }

        public Task StopAsync(CancellationToken cancellationToken)
        {
            _logger.LogInformation($"Consume Scoped Service Hosted Service is stopping. {DateTime.Now}");
            return Task.CompletedTask;
        }
    }

 

然则我真的没搞懂官方这个例子的作用.由于托管效劳只会激活一次,有作用域又有甚么代价呢?愿望哪位老大能解答一下.

 

 

下面的在摘自收集:https://www.cnblogs.com/FlyLolo/p/ASPNETCore2_11.html

经测试:

  1. 当IIS上布置的项目启动后,后台义务随之启动,义务实行响应的log一般输出。

  2. 手动收受接管对应的运用程序池,义务实行响应的log输出住手。

  3. 从新要求该网站,后台义务随之启动,义务实行响应的log从新开始输出。

以是不发起在如许的后台义务中做一些须要流动准时实行的营业措置惩罚类的操纵,但关于缓存革新类的操纵照样能够的,由于当运用程序池收受接管后再次运转的时刻,后台义务会跟着启动。

-玖富娱乐是一家为代理招商,直属主管信息发布为主的资讯网站,同时也兼顾玖富娱乐代理注册登录地址。