private async Task <bool> StopJob() { NLogMgr.DebugLog(_programLog, "收到暂停作业消息"); await PauseScheduler(); return(true); }
/// <summary> /// 添加配置 /// </summary> /// <param name="newConfiguration"></param> /// <returns></returns> public async Task <JsonDataMsg <string> > UserAddConfigurationToToolAsync(ToolConfigDto newConfiguration) { //参数为空检查 if (null == newConfiguration) { NLogMgr.DebugLog(_programLog, "后台接收配置数据失败"); return(new JsonDataMsg <string>(null, false, "后台接收数据失败")); } //使用mapper装换成聚合根 MapperConfiguration cfg = EntityAutoMapper.Instance.AutoMapperConfig(nameof(JobConfiguration)); CheckConfig checkConfig = EntityAutoMapper.Instance.GetMapperResult <CheckConfig>(cfg, newConfiguration); var success = await Repository.AddConfigDataAsync(checkConfig); if (!success) { NLogMgr.DebugLog(_programLog, "增添配置异常"); return(new JsonDataMsg <string>(null, success, "增添配置异常")); } //异步IPC通知工具客户端配置已变化 _client.InvokeAsync(p => p.ConfigWasModify()); NLogMgr.DebugLog(_programLog, "已经为您加入该配置"); return(new JsonDataMsg <string>(null, success, "已经为您加入该配置")); }
public async Task <JsonDataMsg <ExcelPackage> > ExportMachinesAsync() { //先尝试获取100条数据 int current = 1; int capacity = 100; DataBoxDto <EquipmentDto> dataBoxDto = await Repository.QuantitativeTargetsAsync(current, capacity); if (0 == dataBoxDto.Total) { //如果没有数据,则导出一个空的Excel模板文件,并返回 ExcelPackage emptyExcelPackage = ExcelFileService.CreateEquipmentTemplate(); if (null == emptyExcelPackage) { NLogMgr.ErrorExLog(_errorLog, "创建Excel失败", null); return(new JsonDataMsg <ExcelPackage>(null, false, "创建Excel失败")); } NLogMgr.DebugLog(_programLog, "创建Excel模板成功"); return(new JsonDataMsg <ExcelPackage>(emptyExcelPackage, true, "")); } //有数据则根据数据,得到总分页数,便于后续遍历 var totalPage = (int)Math.Ceiling(dataBoxDto.Total * 1.0 / capacity); List <EquipmentDto> eqList = new List <EquipmentDto>(dataBoxDto.Data); if (totalPage > current) { //还需要获取后面分页的数据 while (++current <= totalPage) { dataBoxDto = await Repository.QuantitativeTargetsAsync(current, capacity); if ((null == dataBoxDto.Data || !dataBoxDto.Data.Any()) && (current <= totalPage)) { NLogMgr.ErrorExLog(_errorLog, $"导出第{current}页数据的时候出错了", null); return(new JsonDataMsg <ExcelPackage>(null, false, $"导出第{current}页数据的时候出错了")); } if (null != dataBoxDto.Data && dataBoxDto.Data.Any()) { eqList.AddRange(dataBoxDto.Data); } } } //取完剩余的分页数据,则可以开始生成Excel文件 //todo:生成Excel文件 ExcelPackage excelPackage = ExcelFileService.CreateEquipmentExcel(eqList); if (null == excelPackage) { NLogMgr.ErrorExLog(_errorLog, "创建Excel失败", null); return(new JsonDataMsg <ExcelPackage>(null, false, $"创建Excel失败")); } NLogMgr.DebugLog(_programLog, "数据存储到内存Excel成功"); return(new JsonDataMsg <ExcelPackage>(excelPackage, true, "")); }
private async Task RestartScheduler() { if (null != _scheduler && _scheduler.IsShutdown) { await _scheduler.ResumeJob(new JobKey("ping")); NLogMgr.DebugLog(_programLog, "定时任务恢复工作"); } }
private async Task PauseScheduler() { if (null != _scheduler && _scheduler.IsStarted) { await _scheduler.PauseJob(new JobKey("ping")); NLogMgr.DebugLog(_programLog, "定时任务暂停"); } }
private async Task StopScheduler() { if (null != _scheduler && !_scheduler.IsShutdown) { await _scheduler.Shutdown(); NLogMgr.DebugLog(_programLog, "定时任务结束"); } }
public void OnException(ExceptionContext context) { if (context == null) { return; } //_logger.LogError(context.Exception.Message, context.Exception); NLogMgr.ErrorExLog(_logger, context.Exception.Message, context.Exception); //context.ExceptionHandled = true; }
public async Task <JsonDataMsg <string> > ImportingMachinesAsync(IFormCollection formCollection) { if (null == formCollection || null == formCollection.Files || !formCollection.Files.Any()) { NLogMgr.ErrorExLog(_errorLog, "服务器接收不到文件文件", null); return(new JsonDataMsg <string>(null, false, "服务器接收不到文件")); } IFormFile file = formCollection.Files[0]; if (!ExcelFile.ValidExcelFile(file)) { NLogMgr.DebugLog(_programLog, "您上传的文件不是*.xlsx后缀的文件"); return(new JsonDataMsg <string>(null, false, "您上传的文件不是*.xlsx后缀的文件")); } //导入前通知工具停止作业 NLogMgr.DebugLog(_programLog, "通知工具停止作业"); try { bool ipcResult = await _client.InvokeAsync(p => p.StopJob()); NLogMgr.DebugLog(_programLog, "工具反馈结果:" + ipcResult); } catch (Exception ipcEx) { NLogMgr.ErrorExLog(_errorLog, "ipc通信失败", ipcEx); } List <EquipmentDto> list = await ExcelFileService.GetExcelDataAsync(file); bool success = await Repository.ReplaceTargetsAsync(list); JsonDataMsg <string> result = null; if (success) { NLogMgr.DebugLog(_programLog, "设备导入完毕"); result = new JsonDataMsg <string>(null, success, "设备导入完毕"); } else { NLogMgr.DebugLog(_programLog, "导入设备操作过程发生异常"); result = new JsonDataMsg <string>(null, success, "导入设备操作过程发生异常"); } //导入后重新开始作业 NLogMgr.DebugLog(_programLog, "通知工具可以继续作业"); _client.InvokeAsync(p => p.JobRestart()); return(result); }
private async Task ToolCofigurationModified() { NLogMgr.DebugLog(_programLog, "收到工具配置改动消息"); await PauseScheduler(); await StopScheduler(); if (!await LoadToolParamAsync()) { return; } await ExecuteMissions(); }
public Task StopAsync(CancellationToken cancellationToken) { //throw new NotImplementedException(); StopScheduler(); if (null != _source) { _source.Cancel(); NLogMgr.DebugLog(_programLog, "IpcServer端退出"); } return(Task.CompletedTask); }
public async Task <ToolConfigDto> LoadToolConfigAsync() { NLogMgr.DebugLog(_programLog, "正在加载工具配置"); var toolSetting = await _toolConfigApplication.GetToolValidConfigAsync(); if (null == toolSetting) { NLogMgr.DebugLog(_programLog, "尚未有可用配置,进入等待状态"); //todo:使用定时框架,定时获取配置 return(null); } return(toolSetting); }
//public static IWebHostBuilder CreateWebHostBuilder(string[] args) => // WebHost.CreateDefaultBuilder(args) // .UseStartup<Startup>(); // // .ConfigureLogging(logging => // // { // // logging.ClearProviders(); // // logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace); // // }) // //.UseNLog(); // NLog: setup NLog for Dependency injection; public static IWebHostBuilder CreateWebHostBuilder(string[] args) { NLogMgr.SetVariable(NLogMgr.ConfigurationVariables.Terrace, "测试工具管理后台"); string addressString = ServiceLaunchHelper.GetStartEndpoint(args); //return WebHost.CreateDefaultBuilder(args) // .UseStartup<Startup>(); IWebHostBuilder webHostBuilder = WebHost.CreateDefaultBuilder(args); if (!string.IsNullOrEmpty(addressString)) { webHostBuilder.UseUrls(addressString); } return(webHostBuilder.UseStartup <Startup>()); }
public Task IpcServerRun() { if (null == _ipcServiceHost) { return(Task.CompletedTask); } NLogMgr.DebugLog(_programLog, "IpcServer端启动"); PingServiceContract.ResponseConfigModified += ToolCofigurationModified; PingServiceContract.ResponseJobRestart += JobRestart; PingServiceContract.ResponseStopJob += StopJob; _source = new CancellationTokenSource(); _ipcServiceHost.RunAsync(_source.Token); return(Task.CompletedTask); }
/// <summary> /// 异步Ping远程目标 /// </summary> /// <param name="target">目标</param> /// <param name="timeout">超时时间</param> /// <param name="tryCount">ping的次数</param> /// <returns>方法执行成功返回非空且非空白字符串,否则统一返回空串</returns> public static async Task <string> PingRemoteTargetAsync(IPingable target, int timeout, int tryCount) { string result = string.Empty; try { using (Process process = new Process()) { ProcessStartInfo startInfo = process.StartInfo; startInfo.FileName = _pingCmd.PingName; //对目标执行ping操作四次,超时为1秒 //todao:这里的ping4次数跟超时预设,需要使用数据库配置 if (tryCount < 1) { tryCount = 4; } startInfo.Arguments = string.Format($" {target.IpAddresV4} {_pingCmd.RepeatParam} {tryCount} {_pingCmd.TimeoutParam} {timeout.ToString()}"); //重定向输出流,便于获取ping命令结果 startInfo.RedirectStandardOutput = true; //startInfo.StandardOutputEncoding = Encoding.UTF8; NLogMgr.DebugLog(_programLog, $"执行命令:{_pingCmd.PingName} {startInfo.Arguments}"); //开始执行命令 process.Start(); using (StreamReader reader = process.StandardOutput) { result = await reader.ReadToEndAsync(); //NLogMgr.DebugLog(_programLog, $"{target.Remarks}执行完成===={TimeMgr.GetLoaclDateTime().ToString("yyyy-MM-dd HH:mm:ss:ffff")}===="); //NLogMgr.DebugLog(_programLog, result); //Console.WriteLine($"{target.Remarks}执行完成===={TimeMgr.GetLoaclDateTime().ToString("yyyy-MM-dd HH:mm:ss:ffff")}===="); } } } catch (Exception ex) { //System.Console.WriteLine(ex.Message); NLogMgr.ErrorExLog(_errorLog, "执行Ping操作异常", ex); } return(result); }
public async Task <DataBoxDto <EquipmentDto> > QuantitativeTargetsAsync(int current, int capacity) { try { using (HealthManjuuCoreContext context = new HealthManjuuCoreContext()) { var query = context.MachineInfos.Where(p => p.State != DataState.Disable).AsNoTracking(); if (!await query.AnyAsync()) { return(new DataBoxDto <EquipmentDto>()); } int total = await query.CountAsync(); query.OrderBy(p => p.Id); if (capacity > 0) { query = query.Skip((current - 1) * capacity).Take(capacity); } List <MachineInfo> machineInfos = await query.ToListAsync(); var eqs = EntityAutoMapper.Instance.GetMapperResult <List <EquipmentDto> >(_mapperCfg, machineInfos); if (null == eqs || !eqs.Any()) { NLogMgr.ErrorExLog(_errorLog, " List<MachineInfo> 转换 List<EquipmentDto>失败", null); return(new DataBoxDto <EquipmentDto>()); } var box = new DataBoxDto <EquipmentDto>(); box.Data = eqs; box.Total = total; return(box); } } catch (System.Exception ex) { NLogMgr.ErrorExLog(_errorLog, " 批量获取检测目标异常", ex); return(new DataBoxDto <EquipmentDto>()); } }
public async Task <List <CheckTarget> > GetDataPage(int page) { DataBoxDto <EquipmentDto> dataBoxDto = await _repository.QuantitativeTargetsAsync(CurrentPage, Capacity); if (0 == dataBoxDto.Total) { NLogMgr.DebugLog(_programLog, "首次获取数据,发现没有可检测的目标"); return(null); } if (1 == page) { //有数据则根据数据,得到总分页数,便于后续遍历 TotalPage = (int)Math.Ceiling(dataBoxDto.Total * 1.0 / Capacity); } return(EntityAutoMapper.Instance.GetMapperResult <List <CheckTarget> >(_mapperCfg, dataBoxDto.Data)); }
/// <summary> /// 修改配置 /// </summary> /// <param name="newConfiguration"></param> /// <returns></returns> public async Task <object> UserAlterConfigurationToToolAsync(ToolConfigDto newConfiguration) { //使用mapper装换成聚合根 MapperConfiguration cfg = EntityAutoMapper.Instance.AutoMapperConfig(nameof(JobConfiguration)); CheckConfig checkConfig = EntityAutoMapper.Instance.GetMapperResult <CheckConfig>(cfg, newConfiguration); var success = await Repository.UpdateConfigDataAsync(checkConfig); if (!success) { NLogMgr.DebugLog(_programLog, "更改配置发生异常"); return(new JsonDataMsg <string>(null, success, "更改配置发生异常")); } //异步IPC通知工具客户端配置已变化 _client.InvokeAsync(p => p.ConfigWasModify()); NLogMgr.DebugLog(_programLog, "您已成功更改配置"); return(new JsonDataMsg <string>(null, success, "您已成功更改配置")); }
public async Task <bool> AddConfigDataAsync(CheckConfig config) { try { JobConfiguration jobConfiguration = EntityAutoMapper.Instance.GetMapperResult <JobConfiguration>(_mapperCfg, config); if (null == jobConfiguration) { return(false); } using (HealthManjuuCoreContext context = new HealthManjuuCoreContext()) { return(await AddConfigDataAsync(context, jobConfiguration)); } } catch (System.Exception ex) { NLogMgr.ErrorExLog(_errorLog, "添加检测工具配置异常", ex); return(false); } }
private async Task ExecuteMissions() { _scheduler = await _schedulerFactory.GetScheduler(); Quartz.ITrigger trigger = null; if (RunParam.WorkType == ToolWorkType.AllDay) { //每分钟执行一次 trigger = TriggerBuilder.Create().WithSimpleSchedule(p => p.WithIntervalInMinutes(1)).Build(); } else if (RunParam.WorkType == ToolWorkType.TimeToTime) { string[] start = RunParam.TimeToStart.Split(':'); string[] stop = RunParam.TimeToStop.Split(':'); trigger = TriggerBuilder.Create().WithDailyTimeIntervalSchedule(p => p.OnEveryDay() .StartingDailyAt(TimeOfDay.HourAndMinuteOfDay(int.Parse(start[0]), int.Parse(start[1]))) .EndingDailyAt(TimeOfDay.HourAndMinuteOfDay(int.Parse(stop[0]), int.Parse(stop[1]))) .WithIntervalInSeconds(10)) .Build(); } else { //未支持,立马返回 return; } IJobDetail jobDetail = JobBuilder.Create <PingJob>().WithIdentity("ping", "healthCheck").UsingJobData(new JobDataMap(new Dictionary <string, PingHostedService> { { "runData", this } })).Build(); await _scheduler.Start(); NLogMgr.DebugLog(_programLog, "定时任务开始"); await _scheduler.ScheduleJob(jobDetail, trigger); return; }
public async Task <List <ToolConfigDto> > GetValidConfigsAsync() { try { using (HealthManjuuCoreContext context = new HealthManjuuCoreContext()) { var query = context.JobConfigurations.Where(p => p.State != DataState.Disable).AsNoTracking(); if (!await query.AnyAsync()) { return(null); } List <JobConfiguration> jobList = await query.ToListAsync(); return(EntityAutoMapper.Instance.GetMapperResult <List <ToolConfigDto> >(_mapperCfg, jobList)); } } catch (System.Exception ex) { NLogMgr.ErrorExLog(_errorLog, "获取检测工具配置异常", ex); return(null); } }
/// <summary> /// 尝试异步ping目标地址 /// </summary> /// <param name="timeout">超时时间</param> /// <param name="tryCount">ping的次数</param> /// <returns></returns> public Task TryPingAsync(int timeout, int tryCount) { return(Task.Run(async() => { string pingResult = await CheckTargetService.PingRemoteTargetAsync(this, timeout, tryCount); Console.WriteLine(pingResult); //NLogMgr.DebugLog(_programLog, $"TryPingAsync=>{this.Remarks}调用结束{Environment.NewLine}"); Console.WriteLine($"TryPingAsync=>{this.Remarks}调用结束{Environment.NewLine}"); ////返回空串证明地址ping出了异常 //if (string.IsNullOrWhiteSpace(pingResult)) //{ // //既然已经异常了,就退出当前任务执行,可以考虑统计同一个地址出错次数,一定时间内冻结任务,避免过多的访问不正常的地址 // return; //} CheckReesultInfo checkReesultInfo = await CheckResultService.UnscramblePingResultAsync(IpAddresV4, TargetPort, Remarks, TimeMgr.GetLoaclDateTime(), pingResult); NLogMgr.DebugLog(_programLog, checkReesultInfo.GetResultInfoString()); if (PingResultStatus.Pass == checkReesultInfo.Status) { //NLogMgr.CheckMsgLog(_checkLog, LogLevel.Debug, checkReesultInfo.GetResultInfoString(), pingResult, $"[{this.IpAddresV4}]{this.Remarks}", checkReesultInfo.ResultReceiveTime); return; } //todo:将非正常结果推送到消息队列(考虑开发时间问题,目前先直接写入日志) NLogMgr.CheckMsgLog(_checkLog, LogLevel.Error, checkReesultInfo.GetResultInfoString(), pingResult, $"[{this.IpAddresV4}]{this.Remarks}", checkReesultInfo.ResultReceiveTime); //Console.Clear(); })); }
public static async Task Main(string[] args) { var host = new HostBuilder() .ConfigureHostConfiguration(configHost => { #region Host环境设置 configHost.SetBasePath(Directory.GetCurrentDirectory()); configHost.AddJsonFile("hostsettings.json", optional: true); configHost.AddEnvironmentVariables(prefix: "PREFIX_"); configHost.AddCommandLine(args); #endregion }) .ConfigureAppConfiguration((hostContext, configApp) => { #region 序配置 configApp.AddJsonFile("appsettings.json", optional: true); configApp.AddJsonFile( $"appsettings.{hostContext.HostingEnvironment.EnvironmentName}.json", optional: true); configApp.AddEnvironmentVariables(prefix: "PREFIX_"); configApp.AddCommandLine(args); #endregion }) .ConfigureServices((hostContext, services) => { //程序都在这里注入 #region IRepository var infrastructureAssembly = Assembly.Load("ManjuuInfrastructure"); var repositoryTypes = infrastructureAssembly.GetTypes().Where(p => !p.IsAbstract && typeof(IRepository).IsAssignableFrom(p)); foreach (var item in repositoryTypes) { foreach (var itemIntface in item.GetInterfaces()) { if (typeof(IRepository) == itemIntface) { continue; } services.AddSingleton(itemIntface, item); } } #endregion #region ICustomLog var commonAssembly = Assembly.Load("ManjuuCommon"); var customLogTypes = commonAssembly.GetTypes().Where(p => !p.IsAbstract && typeof(ICustomLog <NLog.ILogger>).IsAssignableFrom(p)); foreach (var item in customLogTypes) { foreach (var itemIntface in item.GetInterfaces()) { if (typeof(ICustomLog <NLog.ILogger>) == itemIntface) { continue; } services.AddSingleton(itemIntface, item); } } #endregion #region IApplication var applicationAssembly = Assembly.Load("ManjuuApplications"); var applicationTypes = applicationAssembly.GetTypes().Where(p => !p.IsAbstract && typeof(IApplication).IsAssignableFrom(p)); foreach (var item in applicationTypes) { foreach (var itemIntface in item.GetInterfaces()) { if (typeof(IApplication) == itemIntface) { continue; } //同一个请求下单例 services.AddScoped(itemIntface, item); } } #endregion #region Quartz.Net services.AddSingleton <ISchedulerFactory, StdSchedulerFactory>(); //注册ISchedulerFactory的实例。 #endregion #region Ipc services.AddLogging(l => { l.AddConsole(); l.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Debug); }) .AddIpc(action => { action.AddNamedPipe(pipeOpt => { pipeOpt.ThreadCount = 2; }).AddService <IDemoServiceContract, DemoServiceContract>() .AddService <ICheckConfigServiceContract, PingServiceContract>() .AddService <ICheckTargetServiceContract, PingServiceContract>(); }); #region Server var ipcServerHost = new IpcServiceHostBuilder(services.BuildServiceProvider()) //.AddNamedPipeEndpoint<IDemoServiceContract>("demoEnpoint", "pipeName") .AddNamedPipeEndpoint <ICheckConfigServiceContract>("ConfigServiceEnpoint", "configPipe") .AddNamedPipeEndpoint <ICheckTargetServiceContract>("TargetServiceEnpoint", "targetPipe") //.AddTcpEndpoint<IDemoServiceContract>("demoTcpEndpoiint", IPAddress.Loopback, 2324) .Build(); services.AddSingleton <IIpcServiceHost>(ipcServerHost); #endregion #region Client IpcServiceClient <ICheckConfigServiceContract> configClient = new IpcServiceClientBuilder <ICheckConfigServiceContract>() .UseNamedPipe("configPipe") // or .UseTcp(IPAddress.Loopback, 45684) to invoke using TCP .Build(); IpcServiceClient <ICheckTargetServiceContract> targetJobClient = new IpcServiceClientBuilder <ICheckTargetServiceContract>() .UseNamedPipe("targetPipe") .Build(); services.AddSingleton <IpcServiceClient <ICheckConfigServiceContract> >(configClient); services.AddSingleton <IpcServiceClient <ICheckTargetServiceContract> >(targetJobClient); #endregion #endregion NLogMgr.SetVariable(NLogMgr.ConfigurationVariables.Terrace, "检测工具"); services.AddHostedService <PingHostedService>(); }) .ConfigureLogging((hostContext, configLogging) => { //日志中间件 //configLogging.AddConsole(); //configLogging.AddDebug(); }) .UseConsoleLifetime() .Build(); await host.RunAsync(); }
private async Task JobRestart() { NLogMgr.DebugLog(_programLog, "收到重新作业消息"); await RestartScheduler(); }
public async Task <bool> UpdateConfigDataAsync(CheckConfig config) { try { if (null == config) { return(false); } JobConfiguration jobConfiguration = EntityAutoMapper.Instance.GetMapperResult <JobConfiguration>(_mapperCfg, config); if (null == jobConfiguration) { return(false); } using (HealthManjuuCoreContext context = new HealthManjuuCoreContext()) { //时间问题,不考虑并发修改问题 using (var transaction = await context.Database.BeginTransactionAsync()) { try { var query = context.JobConfigurations.Where(p => p.Id == config.Id && p.State == DataState.Enable); if (await query.AnyAsync()) { JobConfiguration jobCfg = await query.FirstAsync(); jobCfg.State = DataState.Disable; } jobConfiguration.Id = 0; //数据库会自动生成,把id重置为默认值 bool result = await AddConfigDataAsync(context, jobConfiguration); if (result) { transaction.Commit(); await context.SaveChangesAsync(); } else { transaction.Rollback(); } return(result); } catch (System.Exception ex) { NLogMgr.ErrorExLog(_errorLog, "更新检测工具配置异常", ex); if (null != transaction) { transaction.Rollback(); } return(false); } } } } catch (System.Exception ex) { NLogMgr.ErrorExLog(_errorLog, "执行更新工具配置方法异常", ex); return(false); } }
public async Task <bool> ReplaceTargetsAsync(List <EquipmentDto> equipmentDtos) { try { if (null == equipmentDtos || !equipmentDtos.Any()) { NLogMgr.DebugLog(_programLog, "并没有需要导入的数据"); return(false); } List <MachineInfo> machineInfoList = EntityAutoMapper.Instance.GetMapperResult <List <MachineInfo> >(_mapperCfg, equipmentDtos); if (null == machineInfoList || !machineInfoList.Any()) { NLogMgr.ErrorExLog(_errorLog, " List<EquipmentDto>转换List<MachineInfo>异常", null); return(false); } using (HealthManjuuCoreContext context = new HealthManjuuCoreContext()) { //时间问题,不考虑并发修改问题 using (var transaction = await context.Database.BeginTransactionAsync()) { try { //走这步之前,记得IPC通知客户端通知检测 //Console.WriteLine("重新替换检设备数据,正在删除旧数据"); NLogMgr.DebugLog(_programLog, "重新替换检设备数据,正在删除旧数据"); //把以前的数据清空 var deletedCoount = await context.Database.ExecuteSqlCommandAsync(new RawSqlString($"delete from {nameof(MachineInfo)}s")); //Console.WriteLine($"删除完成,共删除{deletedCoount.ToString()}条数据"); NLogMgr.DebugLog(_programLog, $"删除完成,共删除{deletedCoount.ToString()}条数据"); //Console.WriteLine("进行批量导入数据"); NLogMgr.DebugLog(_programLog, "进行批量导入数据"); await context.MachineInfos.AddRangeAsync(machineInfoList); transaction.Commit(); await context.SaveChangesAsync(); //Console.WriteLine($"成功导入{machineInfoList.Count}条数据"); NLogMgr.DebugLog(_programLog, $"成功导入{machineInfoList.Count}条数据"); return(true); } catch (System.Exception ex) { //System.Console.WriteLine(ex.Message); NLogMgr.ErrorExLog(_errorLog, "批量导入检测目标数据异常", ex); if (null != transaction) { transaction.Rollback(); } return(false); } } } } catch (System.Exception ex) { //System.Console.WriteLine(ex.Message); NLogMgr.ErrorExLog(_errorLog, "方法运行异常", ex); return(false); } }