using System; using System.Threading; using System.Threading.Tasks; using DOAN.Infrastructure.PLC; using DOAN.Model.PBL; using DOAN.Model.System; using Microsoft.Extensions.Hosting; using SqlSugar; using SqlSugar.IOC; namespace DOAN.ServiceCore { public class BackgroundService : IHostedService, IDisposable { private readonly CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource(); private Task _executingTask; public Task StartAsync(CancellationToken cancellationToken) { PLCTool.ConnectPLC(); // 当服务开始时,启动后台任务 _executingTask = ExecuteAsync(_cancellationTokenSource.Token); return _executingTask.IsCompleted ? _executingTask : Task.CompletedTask; } public async Task StopAsync(CancellationToken cancellationToken) { // 请求取消后台任务 _cancellationTokenSource.Cancel(); // 等待后台任务完成 await Task.WhenAny(_executingTask, Task.Delay(Timeout.Infinite, cancellationToken)); } private async Task ExecuteAsync(CancellationToken stoppingToken) { // 获取所有传感器 地址 int index = 1; while (!stoppingToken.IsCancellationRequested) { Storagelocation storagelocation = await DbScoped.SugarScope.CopyNew() .Queryable().Where(it => it.Id == index).FirstAsync(); bool result = PLCTool.ReadBit(storagelocation.PlcAddress2); if (result) { storagelocation.PackageNum = 2; } else { storagelocation.PackageNum = 4; } await DbScoped.SugarScope.CopyNew().Insertable(storagelocation).ExecuteCommandAsync(); // 写补料日志 Inventorylog inventorylog = new Inventorylog(); inventorylog.Id = SnowFlakeSingle.Instance.NextId().ToString(); inventorylog.RackCode = storagelocation.RackCode; index++; if (index > 16) { index = 1; } } } public void Dispose() { PLCTool.ConnectClose(); _cancellationTokenSource.Cancel(); _executingTask.Wait(); _cancellationTokenSource.Dispose(); } } }