using Application.Domain.Entities; using Application.Models; using Infrastructure.Data; using Infrastructure.Extensions; using Microsoft.AspNetCore.SignalR; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace IoTCenter.Services { public class HealthCheckService : IDisposable { internal readonly IServiceProvider _applicationServices; internal readonly IConfiguration _configuration; internal CancellationTokenSource _tokenSource; public HealthCheckService(IServiceProvider applicationServices, IConfiguration configuration) { this._applicationServices = applicationServices; this._configuration = configuration; this._tokenSource = new CancellationTokenSource(); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1031:不捕获常规异常类型", Justification = "<挂起>")] public virtual void Start() { Task.Run(async () => { while (!_tokenSource.IsCancellationRequested) { try { Execute(); } catch (Exception ex) { ex.PrintStack(); } await Task.Delay(5 * 1000); } }); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1031:不捕获常规异常类型", Justification = "<挂起>")] private void Execute() { using var scope = _applicationServices.CreateScope(); var nodeRepo = scope.ServiceProvider.GetService>(); var nodes = nodeRepo.ReadOnlyTable().ToList(); var pageHubContext = scope.ServiceProvider.GetService>(); foreach (var node in nodes) { try { pageHubContext.Clients.Group(node.Number).SendAsync(Methods.ServerToClient, Methods.HealthCheckRequest, "", null); } catch (Exception ex) { ex.PrintStack(); var tempNode = nodeRepo.Table().FirstOrDefault(o => o.Number == node.Number); tempNode.IsOnline = false; nodeRepo.SaveChanges(); } } } public void Dispose() { this._tokenSource.Cancel(); this._tokenSource.Dispose(); } } }