一 PerformanceCounter 基本介紹
1 簡單介紹
表示 Windows NT 效能計數器組件
命名空間:System.Diagnostics
程式集:System(在 system.dll 中)
2 建構函式(只介紹本文要用到的)
PerformanceCounter (String, String, String)
功能:
初始化 PerformanceCounter 類的新的唯讀執行個體,
並將其與本機電腦上指定的系統效能計數器或自訂效能計數器及類別執行個體關聯
參數說明:
public PerformanceCounter (
string categoryName,
string counterName,
string instanceName
)
categoryName
效能計數器關聯的效能計數器類別(效能物件)的名稱。
counterName
效能計數器的名稱。
instanceName
效能計數器類別執行個體的名稱,或者為空白字串 ("")(如果該類別包含單個執行個體)。
二 樣本方法:
需要引用命名空間
using System.Diagnostics;
using System.Threading;
using System.Collections;
1 擷取效能計數器類別列表
雖然系統中有很多可用的計數器類別,但與之互動最頻繁的可能是“Cache”(緩衝)、“Memory”(記憶體)、
“Objects”(對象)、“PhysicalDisk”(物理磁碟)、“Process”(進程)、“Processor”(處理器)、
“Server”(伺服器)、“System”(系統)和“Thread”(線程)等類別
public static void GetCategoryNameList()
{
PerformanceCounterCategory[] myCat2;
myCat2 = PerformanceCounterCategory.GetCategories();
for (int i = 0; i < myCat2.Length; i++)
{
Console.WriteLine(myCat2[i].CategoryName.ToString());
}
}
2 擷取效能計數器類別下的執行個體的名稱執行個體下的效能計數器的名稱
public static void GetInstanceNameListANDCounterNameList(string CategoryName)
{
string[] instanceNames;
ArrayList counters = new ArrayList();
PerformanceCounterCategory mycat = new PerformanceCounterCategory(CategoryName);
try
{
instanceNames = mycat.GetInstanceNames();
if (instanceNames.Length == 0)
{
counters.AddRange(mycat.GetCounters());
}
else
{
for (int i = 0; i < instanceNames.Length; i++)
{
counters.AddRange(mycat.GetCounters(instanceNames[i]));
}
}
for (int i = 0; i < instanceNames.Length; i++)
{
Console.WriteLine(instanceNames[i]);
}
Console.WriteLine("******************************");
foreach (PerformanceCounter counter in counters)
{
Console.WriteLine(counter.CounterName);
}
}
catch (Exception)
{
Console.WriteLine("Unable to list the counters for this category");
}
}
3 根據categoryName,counterName,instanceName獲得效能情況顯示
private static void PerformanceCounterFun(string CategoryName, string InstanceName, string CounterName)
{
PerformanceCounter pc = new PerformanceCounter(CategoryName, CounterName, InstanceName);
while (true)
{
Thread.Sleep(1000); // wait for 1 second
float cpuLoad = pc.NextValue();
Console.WriteLine("CPU load = " + cpuLoad + " %.");
}
}
4 調用方法3顯示cpu使用率
PerformanceCounterFun("Processor", "_Total", "% Processor Time");