重庆熊猫 Loading

ASP.NET Core教程-Configuration(配置)-后台服务

更新记录
转载请注明出处:
2022年11月9日 发布。
2022年11月8日 从笔记迁移到博客。

后台服务说明和作用

后台服务可以实现任务在后台一直运行。可以用于定时处理工作,比如:更新缓存、更新动态、定时发送数据。

后台服务实现方式

可以继承IHostService接口实现自定义后台服务,然后注册到服务容器中。

可以继承BackgroundService类实现自定义后台服务,然后注册到服务容器中。

本质上:BackgroundService类继承自IHostService接口,相当于帮我们封装好了一些功能,提高效率。

注意:BackgroundService类从ASP.NET Core 2.1开始可用。

使用IHostService接口实现自定义后台服务

IHostService 接口的定义

可以看到定义的还是很简单,一个启动操作StartAsync,一个关闭操作StopAsync。

namespace Microsoft.Extensions.Hosting
{
    //
    // 摘要:
    //     Defines methods for objects that are managed by the host.
    public interface IHostedService
    {
        //
        // 摘要:
        //     Triggered when the application host is ready to start the service.
        //
        // 参数:
        //   cancellationToken:
        //     Indicates that the start process has been aborted.
        Task StartAsync(CancellationToken cancellationToken);

        //
        // 摘要:
        //     Triggered when the application host is performing a graceful shutdown.
        //
        // 参数:
        //   cancellationToken:
        //     Indicates that the shutdown process should no longer be graceful.
        Task StopAsync(CancellationToken cancellationToken);
    }
}

定义自定义后台服务

新建PandaHostService.cs文件,并继承自IHostService接口。

namespace Test.HostService
{
    public class PandaHostService : IHostedService
    {
        /// <summary>
        /// 定时器
        /// </summary>
        private Timer Timer { get; set; }
        /// <summary>
        /// 启动
        /// </summary>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public Task StartAsync(CancellationToken cancellationToken)
        {
            this.Timer = new Timer(this.WriteLog,null,TimeSpan.Zero, TimeSpan.FromSeconds(3));
            Console.WriteLine("Panda Host Service Start");
            return Task.CompletedTask;
        }

        /// 模拟要处理的事情
        /// </summary>
        private void WriteLog(object state)
        {
            Console.WriteLine($"Current DateTime {DateTime.Now}");
        }

        /// <summary>
        /// 停止
        /// </summary>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public Task StopAsync(CancellationToken cancellationToken)
        {
            //停止定时器
            this.Timer.Change(Timeout.Infinite, 0);
            Console.WriteLine("Panda Host Service Stop");
            return Task.CompletedTask;
        }
    }
}

注册到服务容器中

builder.Services.AddHostedService<PandaHostService>();

使用BackgroundService类实现自定义后台服务

BackgroundService类的定义

可以看到该类继承自IHostService接口,通常我们只需要实现ExecuteAsync方法即可,还是很方便。如果要大范围的自定义,还不如实现IHostService接口。

namespace Microsoft.Extensions.Hosting
{
    //
    // 摘要:
    //     Base class for implementing a long running Microsoft.Extensions.Hosting.IHostedService.
    public abstract class BackgroundService : IHostedService, IDisposable
    {
        //
        // 摘要:
        //     Gets the Task that executes the background operation.
        //
        // 言论:
        //     Will return null if the background operation hasn't started.
        public virtual Task ExecuteTask
        {
            get
            {
                throw null;
            }
        }

        public virtual void Dispose()
        {
        }

        //
        // 摘要:
        //     This method is called when the Microsoft.Extensions.Hosting.IHostedService starts.
        //     The implementation should return a task that represents the lifetime of the long
        //     running operation(s) being performed.
        //
        // 参数:
        //   stoppingToken:
        //     Triggered when Microsoft.Extensions.Hosting.IHostedService.StopAsync(System.Threading.CancellationToken)
        //     is called.
        //
        // 返回结果:
        //     A System.Threading.Tasks.Task that represents the long running operations.
        protected abstract Task ExecuteAsync(CancellationToken stoppingToken);

        //
        // 摘要:
        //     Triggered when the application host is ready to start the service.
        //
        // 参数:
        //   cancellationToken:
        //     Indicates that the start process has been aborted.
        public virtual Task StartAsync(CancellationToken cancellationToken)
        {
            throw null;
        }

        //
        // 摘要:
        //     Triggered when the application host is performing a graceful shutdown.
        //
        // 参数:
        //   cancellationToken:
        //     Indicates that the shutdown process should no longer be graceful.
        public virtual Task StopAsync(CancellationToken cancellationToken)
        {
            throw null;
        }
    }
}

定义自定义后台服务

只用override一下ExecuteAsync方法即可。

namespace Test.HostService
{
    public class PandaHostService : BackgroundService
    {
        /// <summary>
        /// 定时器
        /// </summary>
        private Timer Timer { get; set; }

        /// <summary>
        /// 实现需要的功能
        /// </summary>
        /// <param name="stoppingToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            Console.WriteLine("Start");

            while(!stoppingToken.IsCancellationRequested)
            {
                this.WriteLog();
                await Task.Delay(TimeSpan.FromSeconds(3), stoppingToken);
            }

            Console.WriteLine("Stop");
        }

        /// <summary>
        /// 模拟要处理的事情
        /// </summary>
        /// <param name="state"></param>
        private void WriteLog()
        {
            Console.WriteLine($"Current DateTime {DateTime.Now}");
        }

    }
}

注册到服务容器中

builder.Services.AddHostedService<PandaHostService>();
posted @ 2022-11-09 09:20  重庆熊猫  阅读(322)  评论(0编辑  收藏  举报