SystemBackgroudService.cs 1.79 KB
using HHECS.DAQServer.Models;

namespace HHECS.DAQServer.Services
{
    public class SystemBackgroundService : BackgroundService
    {
        private readonly IFreeSql _freeSql;
        private readonly DataCacheService _dataCacheService;
        private readonly ILogger<SystemBackgroundService> _logger;
        private readonly int _limit = 1000;

        public SystemBackgroundService(IFreeSql freeSql, DataCacheService dataCacheService, ILogger<SystemBackgroundService> logger)
        {
            _freeSql = freeSql;
            _dataCacheService = dataCacheService;
            _logger = logger;
        }
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            var temps = new List<EquipmentDataRecord>();
            while (!stoppingToken.IsCancellationRequested)
            {
                try
                {
                    if (temps.Count < _limit)
                    {
                        for (int i = 0; i < _limit; i++)
                        {
                            if (_dataCacheService.EquipmentDataRecordQueue.IsEmpty)
                            {
                                break;
                            }
                            _dataCacheService.EquipmentDataRecordQueue.TryDequeue(out var data);
                            temps.Add(data);
                        }
                    }

                    if (temps.Count > 0)
                    {
                        _freeSql.Insert(temps).ExecuteAffrows();
                        temps.Clear();
                    }
                    await Task.Delay(1000, stoppingToken);
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex.Message);
                }
            }
        }
    }
}