Files
Web_CRICS_Server_VS2010_Prod/Common/CPUData.cs

88 lines
2.7 KiB
C#
Raw Normal View History

2025-12-11 09:17:16 +08:00
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace Common
{
public class CPUData
{
public static PerformanceCounter cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total");
public static double GetCPU()
{
2026-03-25 17:51:43 +08:00
try
{
cpuCounter.NextValue(); // 初始化计数器,让它开始计数
System.Threading.Thread.Sleep(1000); // 等待一秒
double cpuUsage = cpuCounter.NextValue(); // 获取CPU使用率
return cpuUsage;
}
catch (Exception ex)
{
throw;
}
2025-12-11 09:17:16 +08:00
}
[DllImport("kernel32.dll")]
private static extern void GetSystemTimePreciseAsFileTime(out long fileTime);
// 将 FILETIME (long) 转换为 DateTime
public static DateTime GetNowPrecise()
{
long fileTime;
GetSystemTimePreciseAsFileTime(out fileTime);
DateTime localTime = DateTime.FromFileTimeUtc(fileTime).ToLocalTime();
return localTime;
}
}
2026-03-25 17:51:43 +08:00
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;
}
}
}
2025-12-11 09:17:16 +08:00
}