程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> 編寫程序 控制cpu占用率-3

編寫程序 控制cpu占用率-3

編輯:C#入門知識

上一節講了通過GetTickCount()控制時間片的切換,然而MS .NET FRAMEWORK還提供了PerformanceCounter這一對象,可以獲得系統資源的各種性能數據,通過這個PerformanceCounter 對象,我們可以更准確的獲得CPU的信息。

上一節連接:http://www.BkJia.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

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved