C#获取CPU信息

 1     /// <summary>
2 /// CPU
3 /// </summary>
4 public class CPULoadInfo
5 {
6 /// <summary>
7 /// 打印CPU信息
8 /// </summary>
9 public static void PrintCPU_Info()
10 {
11 Console.WriteLine(getCPUInfo());
12 }
13 /// <summary>
14 /// 输出CPU信息
15 /// </summary>
16 /// <returns></returns>
17 public static string getCPUInfo()
18 {
19 //总共条数
20 int totalHits = 0;
21 StringBuilder sb = new StringBuilder();
22 int cpuPercent = Convert.ToInt32(getCPUCounter());
23 if (cpuPercent >= 90)
24 {
25 totalHits = totalHits + 1;
26 if (totalHits == 60)
27 {
28 //发送邮件
29 }
30 totalHits = 0;
31 }
32 else
33 {
34 totalHits = 0;
35 }
36 sb.Append(cpuPercent + " % CPU" + "\r\n");
37 //sb.Append(getRAMCounter() + " RAM Free" + "\r\n");
38 sb.Append(totalHits + " seconds over 20% usage" + "\r\n");
39 return sb.ToString();
40 }
41
42 /// <summary>
43 /// 获取CPU信息
44 /// </summary>
45 /// <returns></returns>
46 private static object getCPUCounter()
47 {
48 PerformanceCounter cpuCounter = new PerformanceCounter();
49 cpuCounter.CategoryName = "Processor";
50 cpuCounter.CounterName = "% Processor Time";
51 cpuCounter.InstanceName = "_Total";
52 // will always start at 0
53 dynamic firstValue = cpuCounter.NextValue();
54 System.Threading.Thread.Sleep(1000);
55 // now matches task manager reading
56 dynamic secondValue = cpuCounter.NextValue();
57 return secondValue;
58 }
59 }

 

posted @ 2012-03-19 21:53  石 磊  阅读(6927)  评论(0编辑  收藏  举报