在asp.net core中使用托管服务实现后台任务
在业务场景中经常需要后台服务不停的或定时处理一些任务,这些任务是不需要及时响应请求的。 导入包使用NUGET添加Microsoft.Extensions.Hosting包到项目中 IHostedService接口
取消令牌具有默认的五秒超时,以指示关闭过程不再是正常的。在令牌上请求取消时: 应该中止应用正在执行的任何剩余后台操作。 如果应用程序被意外关闭(例如,应用程序的进程失败),则StopAsync可能无法调用。因此,StopAsync是有可能不会被调用的。 托管服务在应用启动时激活一次,并在应用关闭时正常关闭。为防止异常,最好继承IDispose接口,释放资源 定时后台任务用例可以写一个托管服务类直接继承IHostedService,和IDisposable接口 public class MyTimerHostedService : IHostedService,IDisposable { private Timer _timer; public Task StartAsync(CancellationToken cancellationToken) { Console.WriteLine("启动定时任务托管服务"); _timer = new Timer(DoWork,null,TimeSpan.Zero,TimeSpan.FromSeconds(0.5)); return Task.CompletedTask; } private void DoWork(object state) { Console.WriteLine("定时任务处理中"); } public Task StopAsync(CancellationToken cancellationToken) { _timer?.Change(Timeout.Infinite,0); Console.WriteLine("停止定时任务"); return Task.CompletedTask; } public void Dispose() { // 手动释放定时器 _timer?.Dispose(); } } 该服务Startup.ConfigureServices使用AddHostedService扩展方法注册: services.AddHostedService<MyTimerHostedService>(); 使用通用主机启动 托管服务class Program { static void Main(string[] args) { var host = new HostBuilder().ConfigureServices((hostContext,services) => { services.AddHostedService<MyTimerHostedService>(); }).Build(); host.Run(); Console.WriteLine("Hello World!"); Console.ReadLine(); } } 使用后台服务BackgroundService 实现.NET Core中实现的抽象BackgroundService基类。 // Copyright (c) .NET Foundation. Licensed under the Apache License,Version 2.0. /// <summary> /// Base class for implementing a long running <see cref="IHostedService"/>. /// </summary> public abstract class BackgroundService : IHostedService,IDisposable { private Task _executingTask; private readonly CancellationTokenSource _stoppingCts = new CancellationTokenSource(); protected abstract Task ExecuteAsync(CancellationToken stoppingToken); public virtual Task StartAsync(CancellationToken cancellationToken) { // Store the task we're executing _executingTask = ExecuteAsync(_stoppingCts.Token); // If the task is completed then return it,// this will bubble cancellation and failure to the caller if (_executingTask.IsCompleted) { return _executingTask; } // Otherwise it's running return Task.CompletedTask; } public virtual async Task StopAsync(CancellationToken cancellationToken) { // Stop called without start if (_executingTask == null) { return; } try { // Signal cancellation to the executing method _stoppingCts.Cancel(); } finally { // Wait until the task completes or the stop token triggers await Task.WhenAny(_executingTask,Task.Delay(Timeout.Infinite,cancellationToken)); } } public virtual void Dispose() { _stoppingCts.Cancel(); } } 由于抽象类已经实现了IHostService接口定义的方法,只需要写子类去继承BackgroundService, 在自己的自定义托管服务类中实现ExecuteAsync()方法 public class MyBackGroundService : BackgroundService { protected override async Task ExecuteAsync(CancellationToken stoppingToken) { while (!stoppingToken.IsCancellationRequested) { Console.WriteLine("MyBackGroundService doing"); //延迟500毫秒执行 相当于使用了定时器 await Task.Delay(500,stoppingToken); } } } 在主机中托管服务 class Program { static void Main(string[] args) { var host = new HostBuilder().ConfigureServices((hostContext,services) => { //services.AddHostedService<MyTimerHostedService>(); services.AddHostedService<MyBackGroundService>(); }).Build(); host.Run(); Console.WriteLine("Hello World!"); Console.ReadLine(); } } 使用了HostService后极大的方便了后台任务的管理 github源码地址 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
- asp.net-core-mvc – 区域中的ViewComponents
- ASP脚本中的Python 500服务器错误
- ASP会话算法通过PHP生成cookie
- asp.net-mvc – HttpContext.Current调用背后有多少计算?
- asp.net-core – 如何在部署asp.net核心应用程序时处理环境
- StructureMap和ASP .Net Web API和.Net Framework 4.5
- asp.net-mvc – Microsoft ASP .NET Web API,MVC 4和SPA架构
- asp.net – Kestrel和Katana之间的区别
- asp.net-mvc – 如何使@ Html.EditorFor禁用
- asp.net – 为什么在添加新的响应标头时会出现“平台不支持
- asp.net – 测试ControllerFactory(预启动初始化
- asp.net – IIS作为反向代理 – 从后端服务器压缩
- 如何在ASP.NET中的多个Web应用程序中维护相同的会
- asp.net – 在.net中使用selenium 2.0 web驱动程
- 为什么MVC 5 Owin Oauth没有点击/ Account/Exter
- asp.net – 用于检索大量二进制图像的.ashx处理程
- asp.net-mvc-2 – 未针对请求的URL配置默认文档,
- .net – HttpHandler在IIS 7中不起作用
- asp.net-mvc – 如何在MVC中调用.ashx文件?
- asp.net-mvc – 使用Web API不检查的并发检查