using Microsoft.Extensions.Hosting; using System; using System.Threading; using System.Threading.Tasks; namespace FastGithub.DomainResolve { /// /// 域名的IP测速后台服务 /// sealed class DomainSpeedTestHostedService : BackgroundService { private readonly DomainSpeedTestService speedTestService; private readonly TimeSpan testDueTime = TimeSpan.FromMinutes(1d); /// /// 域名的IP测速后台服务 /// /// public DomainSpeedTestHostedService(DomainSpeedTestService speedTestService) { this.speedTestService = speedTestService; } /// /// 启动时 /// /// /// public override async Task StartAsync(CancellationToken cancellationToken) { await this.speedTestService.LoadDataAsync(cancellationToken); await base.StartAsync(cancellationToken); } /// /// 停止时 /// /// /// public override async Task StopAsync(CancellationToken cancellationToken) { await this.speedTestService.SaveDataAsync(); await base.StopAsync(cancellationToken); } /// /// 后台测速 /// /// /// protected override async Task ExecuteAsync(CancellationToken stoppingToken) { while (stoppingToken.IsCancellationRequested == false) { await this.speedTestService.TestSpeedAsync(stoppingToken); await Task.Delay(this.testDueTime, stoppingToken); } } } }