1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 | /// <summary> /// 监测性能 /// </summary> /// <returns></returns> private bool MonitorPerformance() { bool res = false ; int times = 1; int interval = 1000; //Sleep的时间间隔 TimeSpan prevCpuTime = TimeSpan.Zero; //上次记录CPU的时间 try { while ( true ) { Process[] pros = Process.GetProcessesByName(ProcessName); if (pros.Length > 0) { foreach (Process item in pros) { PerformanceCounter curpc = new PerformanceCounter( "Process" , "Working Set" , item.ProcessName); //当前时间 TimeSpan curCpuTime = item.TotalProcessorTime; //计算 double value = (curCpuTime - prevCpuTime).TotalMilliseconds / interval / Environment.ProcessorCount * 100; prevCpuTime = curCpuTime; //这个工作集是动态更新的 Console.WriteLine( "{0}:{1} {2:N}KB CPU使用率:{3}" , item.ProcessName, "工作集" , curpc.NextValue() / 1024, value); if (value < 5) { res = true ; item.Kill(); } Thread.Sleep(interval); } } else { break ; } if (times * interval == 900000) //十五分钟后超时 { foreach (Process item in pros) { KillProcessAndChildren(item.Id); } break ; } times++; } } catch (Exception ex) { Console.WriteLine( "Function: MonitorPerformance " + ex.Message); } return res; } |
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步