.NET 8 中的后台服务:IHostedService 和 BackgroundService
1..NET 8 中的后台服务:IHostedService 和 BackgroundService
NET 8 引入了强大的功能,用于使用 和 管理后台任务。这些服务使长时间运行的操作(如计划任务、后台处理和定期维护任务)能够无缝集成到您的应用程序中。本文探讨了这些新功能,并提供了实际示例来帮助你入门。您可以在我的 GitHub 存储库中找到这些示例的源代码。IHostedService
BackgroundService
什么是后台服务?
.NET 中的后台服务允许您在后台独立于主应用程序线程运行任务。这对于需要连续或定期运行而不阻塞主应用程序流的任务至关重要。
IHostedService
接口
该接口定义了两种方法:IHostedService
1 StartAsync(CancellationToken cancellationToken):在应用程序主机启动时调用。 2 StopAsync(CancellationToken cancellationToken):在应用程序主机执行正常关闭时调用。
IHostedService
实现示例:
1 using System; 2 using System.Threading; 3 using System.Threading.Tasks; 4 using Microsoft.Extensions.Hosting; 5 using Microsoft.Extensions.Logging; 6 7 public class TimedHostedService : IHostedService, IDisposable 8 { 9 private readonly ILogger<TimedHostedService> _logger; 10 private Timer _timer; 11 12 public TimedHostedService(ILogger<TimedHostedService> logger) 13 { 14 _logger = logger; 15 } 16 17 public Task StartAsync(CancellationToken cancellationToken) 18 { 19 _logger.LogInformation("Timed Hosted Service running."); 20 21 _timer = new Timer(DoWork, null, TimeSpan.Zero, TimeSpan.FromSeconds(5)); 22 23 return Task.CompletedTask; 24 } 25 26 private void DoWork(object state) 27 { 28 _logger.LogInformation("Timed Hosted Service is working."); 29 } 30 31 public Task StopAsync(CancellationToken cancellationToken) 32 { 33 _logger.LogInformation("Timed Hosted Service is stopping."); 34 35 _timer?.Change(Timeout.Infinite, 0); 36 37 return Task.CompletedTask; 38 } 39 40 public void Dispose() 41 { 42 _timer?.Dispose(); 43 } 44 }
BackgroundService
类
该类是一个抽象基类,用于简化后台任务的实现。它提供了一种方法来覆盖:BackgroundService
ExecuteAsync(CancellationToken stoppingToken):
包含后台任务的逻辑,并运行到应用程序关闭为止。
BackgroundService
实现示例:
1 using System; 2 using System.Threading; 3 using System.Threading.Tasks; 4 using Microsoft.Extensions.Hosting; 5 using Microsoft.Extensions.Logging; 6 7 public class TimedBackgroundService : BackgroundService 8 { 9 private readonly ILogger<TimedBackgroundService> _logger; 10 11 public TimedBackgroundService(ILogger<TimedBackgroundService> logger) 12 { 13 _logger = logger; 14 } 15 16 protected override async Task ExecuteAsync(CancellationToken stoppingToken) 17 { 18 _logger.LogInformation("Timed Background Service running."); 19 20 while (!stoppingToken.IsCancellationRequested) 21 { 22 _logger.LogInformation("Timed Background Service is working."); 23 await Task.Delay(TimeSpan.FromSeconds(5), stoppingToken); 24 } 25 26 _logger.LogInformation("Timed Background Service is stopping."); 27 } 28 }
主要区别
-
抽象级别:
IHostedService
:需要手动实现启动和停止逻辑。BackgroundService
:通过提供具有要重写的单个方法的基类来简化实现。
-
使用案例:
IHostedService
:适用于需要对服务生命周期进行精细控制的更复杂的方案。BackgroundService
:非常适合受益于减少样板代码的更简单、长时间运行的任务。
结论
.NET 8 的后台服务(通过 和 )提供了一种可靠且灵活的方式来管理后台任务。通过根据您的需求选择适当的抽象,您可以有效地在应用程序中实现和管理长时间运行的操作。这些新功能增强了创建响应迅速、可伸缩且可维护的 .NET 应用程序的能力。IHostedService
BackgroundService
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek “源神”启动!「GitHub 热点速览」
· 我与微信审核的“相爱相杀”看个人小程序副业
· 上周热点回顾(2.17-2.23)
· 如何使用 Uni-app 实现视频聊天(源码,支持安卓、iOS)
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章