.NET(C#): 在進程PerformanceCounter中擷取進程PID

來源:互聯網
上載者:User

當在進程效能計數器(名稱為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

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.