1. 说明
BackgroundService 是用于实现长时间运行的 IHostedService 的基类,使用程序集:Microsoft.Extensions.Hosting。
2. 实现方式
继承BackgroundService类,然后override ExecuteAsync这个方法,在这个方法内利用while循环执行长时间任务,stoppingToken.IsCancellationRequested判断是否取消, 可以用base.StopAsync(stoppingToken);停止这个任务的执行。
最后需要在 ConfigureService中注册: services.AddHostedService<TestBackService1>();
3. 实战测试
1 public class TestBackService1 : BackgroundService 2 { 3 protected async override Task ExecuteAsync(CancellationToken stoppingToken) 4 { 5 6 while (!stoppingToken.IsCancellationRequested) 7 { 8 try 9 { 10 StreamWriter sw = System.IO.File.AppendText("Log/test.txt"); 11 //追加文本 12 await sw.WriteLineAsync($"当前时间为:{DateTime.Now}");//自动换行 13 sw.Close(); 14 15 await Task.Delay(TimeSpan.FromSeconds(60)); 16 17 //测试报错,进入catch停止后台任务 18 //int.Parse("dsfs"); 19 20 } 21 catch (Exception ex) 22 { 23 StreamWriter sw = System.IO.File.AppendText("Log/test.txt"); 24 await sw.WriteLineAsync($"当前时间为:{DateTime.Now},报错了:{ex.Message}");//自动换行 25 sw.Close(); 26 27 //根据实际业务情况,决定报错了是继续执行还是停止改后台任务 28 //await base.StopAsync(stoppingToken); 29 } 30 } 31 } 32 }
1 public void ConfigureServices(IServiceCollection services) 2 { 3 services.AddControllersWithViews(); 4 5 //注册后台托管服务 6 services.AddHostedService<TestBackService1>(); 7 }
挂在IIS上测试,看会不会中途断掉:
4. 如果要在这个后台服务中使用EF上下文,注入的方式是不好用的,一个是单例的,一个是单次请求的,这个时候要通过下面代码来实现。
!
- 作 者 : Yaopengfei(姚鹏飞)
- 博客地址 : http://www.cnblogs.com/yaopengfei/
- 声 明1 : 本人才疏学浅,用郭德纲的话说“我是一个小学生”,如有错误,欢迎讨论,请勿谩骂^_^。
- 声 明2 : 原创博客请在转载时保留原文链接或在文章开头加上本人博客地址,否则保留追究法律责任的权利。