修改长时间内存会炸
This commit is contained in:
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user