常时间运行的程序 导致系统卡顿 自动监控系统CPU和内存利用率 自动选择 内存回收 软件重启 电脑重启
长时间运行安防系统,导致CPU或内存利用率超80%,使得电脑变的缓慢、卡顿的问题。定时获取CPU和内存利用率的数据,在不同时间段(如凌晨与平时),根据利用率的不同的阈值,进行:内存回收(70%)、重启软件(80%)、重启电脑(90%&凌晨)等操作,以确保电脑和安防系统流畅;此功能可以在配置文件中选择关闭(默认关闭)或开启(根据情况手动开启),利用率的阈值可配置,系统自检频率可配置
appsettings.json 配置文件
{"TimerTick": 0, // [系统自检]频率,单位:毫秒,(0为不检查,60000一分钟,300000五分钟,600000十分钟...)"ConfigTime": "1:00,3:00", //[系统自检]可重启电脑时间,时间从小到大,如 1:00,5:00 即:1点到5点之间,发生卡顿可重启电脑"SwitchKey": "80,85,90", //[系统自检]CPU&内存,利用率阈值,3个数字为一组,数字从小到大,如:80严重,85较严重,90非常严重...70,80,90...80,85,90...
}
MainForm.cs 程序文件
//获取配置
public static int TimerTick = Tools.ToInt32(CustomConfigManager.GetConfig("TimerTick"), 0);
public static string ConfigTime = Tools.ToString(CustomConfigManager.GetConfig("ConfigTime"), "1:00,5:00");
public static string SwitchKey = Tools.ToString(CustomConfigManager.GetConfig("SwitchKey"), "80,85,90");private System.Windows.Forms.Timer timer3;//系统检查//窗口加载
public void MainForm_Load(object sender, EventArgs e)
{if (TimerTick > 0){timer3 = new System.Windows.Forms.Timer();timer3.Interval = TimerTick;timer3.Tick += OnTimeTick3;timer3.Start();}
}//定时程序
private async void OnTimeTick3(object sender, EventArgs e)
{SYS_CHECK();
}//系统检查
public async void SYS_CHECK()
{await Task.Run(() =>{float cpuUsage = GetCpuUsage();//cpu利用率float memoryUsage = GetMemoryUsage();//内存利用率 try{DateTime dt = DateTime.Now;//现在DateTime dt1 = Convert.ToDateTime(dt.ToString("yyyy-MM-dd 01:00:00"));//凌晨1点DateTime dt2 = Convert.ToDateTime(dt.ToString("yyyy-MM-dd 05:00:00"));//凌晨5点if (!string.IsNullOrWhiteSpace(ConfigTime)){string[] arr = ConfigTime.Split(',');if (arr.Length > 1){DateTime dTemp1 = dt1;DateTime dTemp2 = dt2;DateTime.TryParse(dt.ToString($"yyyy-MM-dd {arr[0]}"), out dTemp1);//凌晨1点DateTime.TryParse(dt.ToString($"yyyy-MM-dd {arr[1]}"), out dTemp2);//凌晨5点if (dTemp1 < dTemp2){dt1 = dTemp1;dt2 = dTemp2;}}}int minUsage = 80;//较严重int midUsage = 85;//挺严重int maxUsage = 90;//特严重string[] arrUsage = SwitchKey.Split(',');if (arrUsage.Length > 0 && arrUsage.Length > 2){arrUsage = arrUsage.OrderBy(a => a).ToArray();int.TryParse(arrUsage[0], out minUsage);//小int.TryParse(arrUsage[1], out midUsage);//中int.TryParse(arrUsage[2], out maxUsage);//大}if (dt > dt1 && dt < dt2)//凌晨{if (cpuUsage > midUsage || memoryUsage > midUsage)//85;//挺严重{shutdown();//...重启电脑...}else if (cpuUsage > minUsage || memoryUsage > minUsage)//80;//较严重{restart();//...重启程序...}}else//凌晨以外的时间(千万别重启电脑){if (cpuUsage > maxUsage || memoryUsage > maxUsage)//90;//特严重{restart();//...重启程序...}else if (cpuUsage > midUsage || memoryUsage > midUsage)//85;//挺严重{GC_Collect();//...内存回收...}}}catch { }finally { }});
}//获取CPU利用率
public float GetCpuUsage()
{try{using (PerformanceCounter cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total")){// 开始时间cpuCounter.NextValue();System.Threading.Thread.Sleep(2000); // 等待// 获取CPU使用率float cpuUsage = cpuCounter.NextValue();//Console.WriteLine($"CPU Usage: {cpuUsage}%");//cpuLabel.Text = $"CPU 占用率: {cpuUsage:F2}%";return cpuUsage;}}catch{return 0;}
}//获取内存利用率
public float GetMemoryUsage()
{try{using (var memoryCounter = new PerformanceCounter("Memory", "Available MBytes")){// 获取可用内存(MB)float availableMemory = new PerformanceCounter("Memory", "Available MBytes").NextValue();// 获取系统总物理内存(MB)long totalMemory = (long)new Microsoft.VisualBasic.Devices.ComputerInfo().TotalPhysicalMemory / (1024 * 1024);// 计算内存使用率float memoryUsage = (totalMemory - availableMemory) / totalMemory * 100;//memoryLabel.Text = $"内存占用率: {memoryUsage:F2}%";return memoryUsage;}}catch{return 0;}
}//重启电脑
public void shutdown()
{//...重启电脑...ProcessStartInfo psi = new ProcessStartInfo("shutdown", "/r /f /t 0");// 设置是否使用操作系统外壳程序启动进程psi.UseShellExecute = false;// 创建一个新的进程并启动它Process.Start(psi);
}//重启软件
public void restart()
{string executablePath = Application.ExecutablePath;//本程序路径string arguments = "/skipLogin";//参数:跳过登录Process.Start(executablePath, arguments);//开启一个新的程序Application.Exit();//当前程序关闭退出
}//内存回收
public void GC_Collect()
{GC.Collect();GC.WaitForPendingFinalizers();GC.Collect();
}
Program.cs 程序入口文件
using Dm.filter;
using IntelligentSubstationCore.LightEquipment.LightControl;
using IntelligentSubstationCore.Security;namespace IntelligentSubstationCore
{internal static class Program{[STAThread]static void Main(string[] args){bool skipLogin = false;if (args.Length > 0 && args[0] == "/skipLogin"){skipLogin = true;}if (skipLogin){Application.Run(new AutoLogin());//自动登录页}else{Application.Run(new Login());//登录页面}}}
}
AutoLogin.cs 自动登录 和 Login.cs 手动登录(略)
说明:将之前登录用户的部分登录信息(不包括账号和密码)保存到缓存中(如Redis),取出来验证并自动登录一下,并加载相关数据(AutoLogin.cs大部分代码都在Login.cs里,一样的都执行一遍),跳过登录过程只有数据加载过程,无缝实现软件重启,释放内存、缓存、Redis等...
如果模拟登录AutoLogin.cs失败(验证失败、登录失败、token失败...),则强行进入登录页面Login.cs 重新登录...
强行重启电脑
ProcessStartInfo psi = new ProcessStartInfo("shutdown", "/r /f /t 0");
是 C# 中用于启动系统关机命令的代码,其中的参数对应 Windows 系统的
shutdown
命令选项。以下是各参数的详细说明:
shutdown
命令基本语法plaintext
shutdown [/参数1] [/参数2] [...]
关键参数解析
1.
/r
:重启计算机
- 作用:执行重启操作,等同于先关机再开机。
- 替代参数:
/s
:仅关机(不重启)。/l
:注销当前用户(相当于 “退出登录”)。2.
/f
:强制关闭程序
- 作用:强制关闭所有未响应的应用程序,不显示确认提示。
- 场景:当程序无响应或需要快速重启时使用。
- 注意:可能导致未保存的数据丢失。
3.
/t 0
:设置超时时间
/t
:指定执行操作前的等待秒数(超时时间)。0
:立即执行,无延迟。