using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Configuration;
using System.Data.Entity;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using XdCxRhDW.Dto;
using XdCxRhDW.Entity;
using XdCxRhDW.Repostory;
namespace XdCxRhDW.App
{
///
/// 两星一地定位取参考服务
///
public class X2D1PosRefService
{
public static X2D1PosRefService Instance { get; private set; } = new X2D1PosRefService();
readonly List handles = new List();
public double TakeRefTime;
public X2D1PosRefService()
{
double.TryParse(ConfigurationManager.AppSettings["TakeRefTime"], out TakeRefTime);
if (TakeRefTime < 0)
{
TakeRefTime = 30;
}
StartMonitor();
}
public void StartMonitor()
{
Task.Run(() =>
{
while (true)
{
if (handles.Count == 0)
{
Thread.Sleep(5000);
}
try
{
lock (this)
{
List deletes = new List();
using (RHDWContext db = new RHDWContext())
{
for (int i = 0; i < handles.Count; i++)
{
var handle = handles[i];
var runTask = db.TaskInfos.FirstOrDefault(p => p.ID == handle.TaskId && p.TaskState == EnumTaskState.Running);
if (runTask == null)
{
handle.Stop();
deletes.Add(handle);
}
}
}
//删除未运行的任务
handles.RemoveAll(r => deletes.Any(d => d.TaskId == r.TaskId));
}
Thread.Sleep(5000);
}
catch (Exception ex)
{
Serilog.Log.Error(ex, $"【监视取参考任务运行状态异常,{ex.Message}");
}
}
});
}
public void AddPosDto(X2D1NoXlNoParlPosDto dto)
{
try
{
lock (this)
{
var firstDto = handles.FirstOrDefault(m => m.TaskId == dto.TaskID);
if (firstDto == null)
{
firstDto = new X2D1PosHandle(dto.TaskID.Value,TakeRefTime);
handles.Add(firstDto);
}
firstDto.Append(dto);
}
}
catch (Exception ex)
{
Serilog.Log.Error(ex, $"【任务{dto.TaskID}】添加取参考信号流程异常,{ex.Message}");
}
}
public void Stop(int taskID)
{
try
{
lock (this)
{
var firstDto = handles.FirstOrDefault(m => m.TaskId == taskID);
if (firstDto != null)
{
firstDto.Stop();
handles.Remove(firstDto);
}
}
}
catch (Exception ex)
{
Serilog.Log.Error(ex, $"停止【任务{taskID}】取参考信号流程异常,{ex.Message}");
}
}
}
}