代码改变世界

有关C#获取当前进程资源简况

2011-01-15 01:39  咸蛋哥哥  阅读(462)  评论(0编辑  收藏  举报

在论坛上看到一个问题,要求是取得当前进程相关的占用简况,但是为什么取cpu占用时总返回0呢?lz的代码是这样的:

 

代码
1 while (true)
2 { // Process[] p = Process.GetProcessesByName("");
3   Process[] p = Process.GetProcesses();//获取所有进程信息
4  
5 string cpu = string.Empty;
6 string info = string.Empty;
7 PerformanceCounter pp = new PerformanceCounter();
8
9
10 if (p.Length > 0)
11 {
12 foreach (Process pr in p)
13 {
14 pp = new PerformanceCounter();
15 pp.CategoryName = "Process";
16 pp.CounterName = "% Processor Time";
17 pp.MachineName = ".";
18 pp.InstanceName = pr.ProcessName;
19
20 LogUtil.PrintLn("进程名:" + pr.ProcessName);
21 Thread.Sleep(1000);
22 cpu = "CPU:" + Math.Round(pp.NextValue(), 2).ToString() + "%";
23 LogUtil.Print(cpu);
24 LogUtil.PrintLn(" 内存:" + (Convert.ToInt64(pr.WorkingSet64.ToString()) / 1024).ToString());
25 }
26 }
27 Thread.Sleep(1000*10);
28 }
29 }
30
31
32  

 

 

在.Net 相关的方法和对象都是现成的,只需要读取出来即可。但是PerformanceCounterNextValue方法第一次是用来初始化此对象的,所以其返回值一定是0(这里我也想不明白为什么?NextValue的方法,延迟下再取一次就可以取到值了,是不是"延迟赋值"?有了解的朋友麻烦告知下)。所以上面lz的代码取得一直都会是0.

略修改下,把相关的对象事先创建好.当然,这些不是最好的方法,只是做演示,有不好之处请多指正:

 

代码
1 static void Main(string[] args)
2 {
3 PerformanceCounter pp = null;
4 Process[] p = Process.GetProcesses();//进程信息
5   Dictionary<PerformanceCounter, long> tList = new Dictionary<PerformanceCounter, long>();
6 Action ac = () =>
7 {
8 if (p.Length > 0)
9 {
10
11 foreach (Process pr in p)
12 {
13 pp = new PerformanceCounter();
14 pp.CategoryName = "Process";
15 pp.CounterName = "% Processor Time";
16 pp.MachineName = ".";
17 string processName = pr.ProcessName;
18 pp.InstanceName = processName;
19 if (!tList.ContainsKey(pp) && processName.ToLower()!="idle")//空闲信息就不显示了
20   {
21 tList.Add(pp, pr.WorkingSet64);
22 pp.NextValue(); //这对象初次返回的都是0,这里当初始化一次
23   }
24 }
25 }
26 };
27 ac(); //初始化对象
28   int cpuCount = Environment.ProcessorCount;//机子CPU数
29   while (true)
30 {
31 foreach (KeyValuePair<PerformanceCounter, long> pr in tList)
32 {
33 float cpuV = (pr.Key.NextValue()) / cpuCount;
34 string cpuPrecent = Math.Round(cpuV, 2).ToString();
35 long memoryValue = (pr.Value / 1024);
36 if (cpuV > 0) //指定cpu有占用的变色
37   {
38 Console.ForegroundColor = ConsoleColor.Red;
39 Console.WriteLine("[{0}]: cpu使用{1}%,内存使用{2}KB", pr.Key.InstanceName, cpuPrecent, memoryValue);
40 }
41 else
42 {
43 Console.ForegroundColor = ConsoleColor.White;
44 Console.WriteLine("[{0}]: cpu使用{1}%,内存使用{2}KB", pr.Key.InstanceName, cpuPrecent, memoryValue);
45 }
46 Thread.Sleep(100);
47 }
48 Thread.Sleep(1000 * 10);
49 ac(); //为了实时取当前的进程,再次创建
50   Console.Clear();
51 }
52
53 }

 

PS: 很久不写博客了,虽然这些文章没什么含量,但就当培养下自己写博的习惯呃,呵呵