/// <summary> /// 执行数据采集命令 /// </summary> /// <param name="m"></param> /// <returns></returns> [HttpPost] [Route("DataAcquisitionAuto")] public async Task<MessageModel<string>> DataAcquisitionAuto(ProcedureParameterRecordDTO m) { //① 启动任务:点击一个采集按钮时,启动对应的任务。 //② 停止任务:如果点击当前正在进行的按钮,触发停止功能,并获取任务的执行时间。 //③ 管理任务:点击新的按钮时,需要停止表单其他所有正在进行的任务,只保留当前点击的任务。 Log4netHelper.Info("执行数据采集命令", "DataAcquisitionAuto", HelperTools.ConvertToJson(m)); var retValue = new MessageModel<string>() { status = (int)StatusEnum.NO }; var loginUser = JwtHelper.GetUserInfo(HttpContext.AuthenticateAsync().Result); //生成唯一标识符 string taskId = $"{loginUser.UserCode}_{m.Nid}_{m.FormGuid}"; try { var StepName = ""; //获取采集信息 var dataColConfigFirst = await db.Queryable<DataColWorkstepEntity>().Where(a => a.Nid == m.Nid).FirstAsync(); if (dataColConfigFirst != null) { StepName = dataColConfigFirst.StepName; #region 记录最后一次按钮情况 //记录最新一次按钮情况 var parmeterGatherInfo = await db.Queryable<ProcedureParameterRecordEntity>() .FirstAsync(x => x.FormGuid == m.FormGuid && x.ParameterName == "LatestCollection"); if (parmeterGatherInfo == null) { var parmeterGather = new ProcedureParameterRecordDTO(); HelperTools.ExchangeEntity(parmeterGather, m); parmeterGather.CollectionStep = StepName; parmeterGather.CollectionTime = DateTime.Now; parmeterGather.ParameterValue = StepName; parmeterGather.ParameterName = "LatestCollection"; parmeterGather.Nid = HelperTools.GetGuid(); parmeterGather.IsDelete = 0; parmeterGather.CreateTime = DateTime.Now; parmeterGather.CreateUserCode = loginUser.UserCode; parmeterGather.CreateUserName = loginUser.UserName; parmeterGather.CreateUserId = loginUser.UserId; //parmeterGather.CollectionName = item.TableName; parmeterGather.FormName = dataColConfigFirst.FormName; parmeterGather.FormGuid = m.FormGuid; parmeterGather.FormRemark = m.FormRemark; var parmeter = new ProcedureParameterRecordEntity(); HelperTools.ExchangeEntity(parmeter, parmeterGather); await db.Insertable(parmeter).ExecuteCommandAsync(); } else { if (parmeterGatherInfo.ParameterValue == m.StepName) { parmeterGatherInfo.ParameterValue = ""; } else { //已存在则更新 parmeterGatherInfo.ParameterValue = m.StepName; } await db.Updateable(parmeterGatherInfo).ExecuteCommandAsync(); } #endregion } // 匹配当前任务是否已在执行中,如果存在则将当前任务取消 if (TaskDictionary.TryGetValue(taskId, out var existingTaskInfo)) { // 记录取消时间 var cancelTime = DateTime.Now; // 如果任务已经存在,取消当前任务 existingTaskInfo.Cts.Cancel(); try { await existingTaskInfo.Task; // 确保任务完成或取消 } catch (OperationCanceledException) { // 处理任务取消 Log4netHelper.Info("任务已被取消"); } catch (Exception ex) { Log4netHelper.Info(ex.Message); } //最大采集时间 var maxGather = new DateTime(); var startTimeCurr = existingTaskInfo.StartTime; //获取最大采集时间 maxGather = startTimeCurr.AddHours(Convert.ToDouble(existingTaskInfo.CollectionDurationthis)); var elapsed = cancelTime - existingTaskInfo.StartTime; // 将 TimeSpan 转换为时分秒格式 string elapsedTimeFormatted = string.Format("{0:D2}:{1:D2}:{2:D2}", elapsed.Hours, elapsed.Minutes, elapsed.Seconds); TaskDictionary.TryRemove(taskId, out _); return new MessageModel<string>() { success = false, msg = $"任务已停止,{StepName}【{existingTaskInfo.StartTime.ToString("MM月dd日HH:mm:ss")}/{maxGather.ToString("MM月dd日HH:mm:ss")}】,已采集时间【{elapsedTimeFormatted}】!" }; } //取消当前表单其他所有正在运行的任务 foreach (var key in TaskDictionary.Keys) { //只取消当前表单的任务 if (!key.Contains(m.FormGuid)) continue; var taskInfo = TaskDictionary[key]; taskInfo.Cts.Cancel(); // 取消任务 try { await taskInfo.Task; // 等待任务完成或取消 } catch (OperationCanceledException) { // 处理任务取消 Log4netHelper.Info("任务已被取消"); } catch (Exception ex) { Log4netHelper.Info(ex.Message); } TaskDictionary.TryRemove(key, out _); } // 创建新的取消令牌源 var cts = new CancellationTokenSource(); // 启动新任务 Task<MessageModel<string>> task = Task.Run(async () => { // 记录任务开始时间 var startTime = DateTime.Now; // 开始采集任务 // 确保 DataAcquisitionAuto 在异步上下文中运行 var result = await dataAcquisitionServer.DataAcquisitionAuto(m, loginUser, cts.Token); Log4netHelper.Info("数采执行结果-------" + HelperTools.ConvertToJson(result)); return result; }, cts.Token); // 存储新任务及其取消令牌源到字典中 TaskDictionary[taskId] = (task, cts, DateTime.Now, m.CollectionDurationthis); retValue.success = true; retValue.msg = "成功"; //UpdateLogValue(NID, retValue); Log4netHelper.Info("执行方法成功,即将返回数据!"); } catch (Exception ex) { retValue.msg = ex.Message; Log4netHelper.Error("执行数据采集命令", "DataAcquisitionAuto", HelperTools.ConvertToJson(ex.Message)); } return retValue; }
/// <summary> /// 获取数采配置信息 /// </summary> /// <param name="m"></param> /// <returns></returns> [HttpPost] [Route("GetDataColWorkstepInfo")] public async Task<DataColWorkstepDTO> GetDataColWorkstepInfo(ProcedureParameterRecordDTO m) { var result = await dataAcquisitionServer.GetDataColWorkstepInfo(m); return result; }
#region 获取数采配置信息 /// <summary> /// 获取数采配置信息 /// </summary> /// <param name="query"></param> /// <returns></returns> public async Task<DataColWorkstepDTO> GetDataColWorkstepInfo(ProcedureParameterRecordDTO query) { var data = await BaseDal.Db.Queryable<DataColWorkstepEntity>() .OrderByDescending(x => x.CreateTime) .WhereIF(!string.IsNullOrEmpty(query.Nid), x => x.Nid == query.Nid) .FirstAsync(); //获取记录最新一次按钮情况 var parmeterGatherInfo = await BaseDal.Db.Queryable<ProcedureParameterRecordEntity>() .FirstAsync(x => x.FormGuid == query.FormGuid && x.ParameterName == "LatestCollection"); if (data == null) return new DataColWorkstepDTO(); // 数据转换 var dto = _mapper.Map<DataColWorkstepDTO>(data); if (parmeterGatherInfo != null) { dto.LatestCollection = parmeterGatherInfo.ParameterValue; } return dto; } #endregion
标签:异步,parmeterGatherInfo,C#,await,FormGuid,采集,任务,var,parmeterGather From: https://www.cnblogs.com/sssyyds/p/18433157