當在進程效能計數器(名稱為Process的PerformanceCounter)中列舉執行個體名稱時,你會發現:為了區別相同的進程名稱,返回進程名稱可能是xxx#1,xxx#2……代表著第一個重複名稱的xxx進程,第二個重複名稱的xxx進程。
比如這段代碼:
var category = new PerformanceCounterCategory("Process");
string[] names = category.GetInstanceNames();
結果(在我的電腦上):
svchost多個進程被#xxx所標識以避免相同名稱。
問題隨之而來,這樣直接顯示出來既在名稱上不美觀,而且我們根本不知道上面的一堆svchost#xxx具體是哪個svchost,它們是按什麼邏輯編號的也無從得知。怎樣把PerformanceCounter返回的不規則進程名轉換成它所代表的進程對象?
解鈴還須繫鈴人……解決方案還是靠Process類型的PerformanceCounter。此時依靠另一個計數器:ID Process,它可以返回一個進程的PID,這樣的話,通過這些名稱就可以查詢他的PID了,有了PID,它所代表的進程就可以輕鬆找到了。
比如這段代碼(只為了示範,根據自己需要請另作修改)
//+ using System.Diagnostics
static void Main()
{
var category = new PerformanceCounterCategory("Process");
string[] names = category.GetInstanceNames().Select(name =>
{
var counter = new PerformanceCounter("Process", "ID Process", name);
var id = counter.NextValue();
return String.Format("PID: {0} - {1}", id, TrimString(name));
}).ToArray();
}
//嘗試去掉進程名稱中的#字元
static string TrimString(string name)
{
var pos = name.IndexOf('#');
if (pos != -1)
return name.Substring(0, pos);
return name;
}
兩段代碼查詢結果:
目前的版本的程式和原始碼下載
下載頁面
注意:連結是微軟SkyDrive頁面,下載時請用瀏覽器直接下載,用某些下載工具可能無法下載
原始碼環境:Visual C# Express 2010