1 class CpuHelper 2 { 3 4 #region 变量、属性 5 private static float cpuRate=0f;//声明cpu使用率变量 6 7 public static float CpuRate 8 { 9 get { return cpuRate; } 10 set { cpuRate = value; } 11 } 12 private static Thread hThread = null;//获取CPU使用率的线程 13 private static bool isRunning = false;//线程状态的标志 14 15 private const string CategoryName = "Processor"; 16 private const string CounterName = "% Processor Time";//PerformanceCounter三个参数 17 private const string InstanceName = "_Total"; 18 19 #endregion 20 21 #region 获取CPU硬件信息 22 23 /// <summary> 24 /// 获取当前电脑CPU的频率 25 /// </summary> 26 /// <returns></returns> 27 public static int GetCPUFrequency() 28 { 29 RegistryKey r = Registry.LocalMachine.OpenSubKey(@"HARDWAREDESCRIPTIONSystemCentralProcessor "); 30 object c = r.GetValue("~MHz"); 31 int CpuFrequency = (int)c; 32 return CpuFrequency; 33 } 34 35 36 #endregion 37 38 #region 获取CPU的使用率 39 /// <summary> 40 /// 获取CPU使用率信息,由于CPU使用率是即时信息,采用线程获取 41 /// </summary> 42 /// <returns></returns> 43 public static float GetCpuRate() 44 { 45 if (!isRunning && hThread == null) 46 { 47 isRunning = true; 48 hThread = new System.Threading.Thread(new System.Threading.ThreadStart(CpuWork)); 49 if (hThread != null) 50 { 51 hThread.Start(); 52 } 53 } 54 return cpuRate; 55 } 56 57 /// <summary> 58 /// 停止获取线程 59 /// </summary> 60 public static void StopGetCpuWork() 61 { 62 isRunning = false; 63 64 if (hThread != null) 65 { 66 if (hThread.IsAlive) 67 hThread.Abort(); 68 69 hThread = null; 70 } 71 } 72 73 /// <summary> 74 /// 75 /// </summary> 76 private static void CpuWork() 77 { 78 try 79 { 80 PerformanceCounter pc = new PerformanceCounter(CategoryName, CounterName, InstanceName); 81 while (isRunning) 82 { 83 System.Threading.Thread.Sleep(1000); // wait for 1 second 84 float cpuLoad = pc.NextValue(); 85 cpuRate = cpuLoad; 86 } 87 } 88 catch (Exception ex) 89 { 90 Console.WriteLine("获取CPU工作线程方法 异常:" + ex.Message); 91 } 92 } 93 94 #endregion 95 }