修改长时间内存会炸

This commit is contained in:
2026-03-25 17:51:43 +08:00
parent 1840794f40
commit d0c626c189
61 changed files with 82737 additions and 271 deletions

View File

@@ -12,10 +12,17 @@ namespace Common
public static PerformanceCounter cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total");
public static double GetCPU()
{
cpuCounter.NextValue(); // 初始化计数器,让它开始计数
System.Threading.Thread.Sleep(1000); // 等待一秒
double cpuUsage = cpuCounter.NextValue(); // 获取CPU使用率
return cpuUsage;
try
{
cpuCounter.NextValue(); // 初始化计数器,让它开始计数
System.Threading.Thread.Sleep(1000); // 等待一秒
double cpuUsage = cpuCounter.NextValue(); // 获取CPU使用率
return cpuUsage;
}
catch (Exception ex)
{
throw;
}
}
[DllImport("kernel32.dll")]
@@ -31,4 +38,50 @@ namespace Common
}
}
public class CpuMonitor
{
// 将静态初始化改为延迟加载,并将异常处理移至初始化时
private static PerformanceCounter _cpuCounter = null;
private static readonly object _lock = new object();
private static Exception _initException = null;
private static void InitializeCounter()
{
if (_initException != null) throw _initException;
if (_cpuCounter != null) return;
lock (_lock)
{
if (_cpuCounter != null) return;
try
{
// 尝试创建计数器
_cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total");
// 立即调用一次 NextValue 来初始化
_cpuCounter.NextValue();
}
catch (Exception ex)
{
throw _initException;
}
}
}
public static double GetCurrentCpuUsage()
{
try
{
CpuMonitor.InitializeCounter(); // 确保计数器已初始化
_cpuCounter.NextValue(); // 首次调用返回0用于初始化本次采样
System.Threading.Thread.Sleep(1000); // 等待采样间隔
return _cpuCounter.NextValue(); // 返回过去一秒内的平均使用率
}
catch
{
// 记录日志或返回一个错误标识值,例如 -1
return -1;
}
}
}
}