当前位置:编程学习 > C#/ASP.NET >>

编写程序 控制cpu占用率-3

上一节讲了通过GetTickCount()控制时间片的切换,然而MS .NET FRAMEWORK还提供了PerformanceCounter这一对象,可以获得系统资源的各种性能数据,通过这个PerformanceCounter 对象,我们可以更准确的获得CPU的信息。

上一节连接:http://www.zzzyk.com/kf/201110/107757.html

 

view plain
using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Diagnostics; 
 
namespace cpu_3_csharp 

    class Program 
    { 
        static void Main(string[] args) 
        { 
            float level=150F; 
            PerformanceCounterCategory[] test = PerformanceCounterCategory.GetCategories(); 
            for (int i = 0; i < test.Length; i++) 
            { 
                //Console.WriteLine(test[i].CategoryName); 
                if (test[i].CategoryName == "Processor") 
                { 
                    string[] temp = test[i].GetInstanceNames(); 
                    //Console.WriteLine(temp.Length); 
                    for (int j = 0; j < temp.Length; j++) 
                    { 
                        Console.WriteLine(test[i].MachineName); 
                        Console.WriteLine("------------------------"); 
                        Console.WriteLine(temp[j]); 
                        Console.WriteLine("------------------------"); 
 
                        PerformanceCounter[] counters = test[i].GetCounters(temp[j]); 
                        for (int k = 0; k < counters.Length; k++) 
                        { 
                            Console.WriteLine(counters[k].CounterName); 
                        } 
                    } 
                } 
            } 
 
            Console.WriteLine("*******************************************************"); 
 
            PerformanceCounter p = new PerformanceCounter("Processor","% Processor Time","_Total"); 
            Console.WriteLine(p.NextValue()); 
            while (true) 
            { 
                //Console.WriteLine(p.NextValue()); 
                if (p.NextValue() > level) 
                { 
                    System.Threading.Thread.Sleep(10); 
                } 
            } 
        } 
    } 

在 Console.WriteLine("*******************************************************"); 语句前的操作暂时不用管,因为我是测试用的。

通过设定一个level值,当CPU的使用率超过这个值以后让其休眠,否则进行不停的空循环。

 

但是结果并不是理想,因为同样像上一节那样出现了一个内核繁忙一个内核空闲的现象,稍后将解决双核处理器的问题。

 \

摘自:Watkins.Song chanllege yourself

补充:软件开发 , C# ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,