.net core 3.1 服务承载【BackgroundService】 电脑版发表于:2021/2/7 22:23 ![.netcore](https://img.tnblog.net/arcimg/hb/c857299a86d84ee7b26d181a31e58234.jpg ".netcore") >#.net core 3.1 服务承载【BackgroundService】 [TOC] 目录 ------------ tn>https://www.tnblog.net/hb/article/details/5591 内容 ------------ tn>在`.net core 2.1`后出了一个抽象类`BackgroundService`实现了`IHostedService`类的功能,并通过实现`ExecuteAsync`抽象方法实现后台长时间执行的效果。这里我们使用`PerformanceMetricsBackgroundService`的类去实现`BackgroundService`这个抽象类的`ExecuteAsync`方法,去实现与`PerformanceMetricsCollector`一样的效果。 ```csharp public class PerformanceMetricsBackgroundService : BackgroundService { private readonly IProcessorMetricsCollector _processorMetricsCollector; private readonly INetworkMetricsCollector _networkMetricsCollector; private readonly IMetricsDeliverer _metricsDeliverer; private readonly IMemoryMetricsCollector _memoryMetricsCollector; private readonly IOptions<MetricsCollectionOptions> _optionsAccessor; private readonly ILogger<PerformanceMetricsBackgroundService> _logger; public PerformanceMetricsBackgroundService( IProcessorMetricsCollector processorMetricsCollector, INetworkMetricsCollector networkMetricsCollector, IMetricsDeliverer metricsDeliverer, IMemoryMetricsCollector memoryMetricsCollector, IOptions<MetricsCollectionOptions> optionsAccessor, ILogger<PerformanceMetricsBackgroundService> logger ) { _processorMetricsCollector = processorMetricsCollector; _networkMetricsCollector = networkMetricsCollector; _metricsDeliverer = metricsDeliverer; _memoryMetricsCollector = memoryMetricsCollector; _optionsAccessor = optionsAccessor; _logger = logger; } protected override async Task ExecuteAsync(CancellationToken stoppingToken) { while (!stoppingToken.IsCancellationRequested) { try { // 执行的方法 await Callback(); } catch (Exception ex) { _logger.LogError(ex,$"Job {nameof(PerformanceMetricsBackgroundService)} threw an exception!"); } // 间隔的时间 await Task.Delay(_optionsAccessor.Value.CaptureInterval); } } private async Task Callback() { // 通过不同指标获取实例 var performanceMetrics = new PerformanceMetrics() { Memory = _memoryMetricsCollector.GetUsage(), Network = _networkMetricsCollector.GetThroughput(), Processor = _processorMetricsCollector.GetUsage() }; await _metricsDeliverer.DeliverAsync(performanceMetrics); } } ``` tn>注册服务 ```csharp .AddSingleton<IHostedService, PerformanceMetricsBackgroundService>() ``` tn>测试 ![](https://img.tnblog.net/arcimg/hb/20b4ca97ade947069d2e9bfb87ef34ae.png) tn>我们来分析一下`BackgroundService`的源代码 ![](https://img.tnblog.net/arcimg/hb/139210ac9f4649579d1b31cefa1004d8.png) BackgroundService的优点 ------------ | 优点 | | ------------ | | 可以快速的实现后台任务 | | 不会阻塞应用启动(除非重写`StartAsync`) | BackgroundService的缺点 ------------ | 缺点 | | ------------ | | 不适合占用资源多的后台任务 | | 不适合实现太多的后台任务(可能会影响性能) | | Web应用水平扩展时会遇到幂等性问题 |