2013-04-02 27 views
2

我正在用C#編寫一個使用.NET 4.5的程序,這將允許我監視特定進程的內存,CPU和網絡使用情況,然後根據我的需求。Process.PrivateMemorySize64返回提交的內存而不是私有的

爲了獲得某個特定進程的內存使用情況,我正在檢查該Process對象的PrivateMemorySize64屬性。我希望看到該進程使用的專用內存,但實際上它顯示了「提交」中的金額,這由Windows資源監視器確認。

我的問題是:

1)有人知道爲什麼會出現這個錯誤嗎? 2)有沒有修復它? 3)如果沒有修復,是否有另一種直接的方式可以獲得爲進程保留的私有內存?

這裏是我的代碼的相關部分:

using System; 

// I add all the open Processes to an array 
Process[] localAll = Process.GetProcesses(); 

// I then add all the processes to a combobox to select from 
// There's a button that updates labels with requested info 

Process[] p = Process.GetProcessesByName(comboBox1.SelectedItem.ToString()); 
label1.Text = p[0].PrivateMemorySize64.ToString() + " bytes"; 
+1

一次again..hard告訴什麼是錯的時候,我們不能看到你正在使用..它肯定會有助於工作,以顯示你的代碼 – MethodMan

+0

代碼從閱讀的文檔'PrivateMemorySize64'中,提交大小正是我期望它返回的。 「私人記憶」是什麼意思?你在談論私人工作組嗎? –

+0

是的,我的意思是私人工作集。我對這種含糊之處表示歉意。 – fakeplasticandroid

回答

0

從您的評論你說你正在尋找私人工作集。從這個鏈接How to calculate private working set (memory)? 看來,它確實不是Process類的一部分。你必須改用性能計數器。

從其他答案複製和粘貼,以防萬一由於某種原因被刪除。

using System; 
using System.Diagnostics; 

class Program { 
    static void Main(string[] args) { 
     string prcName = Process.GetCurrentProcess().ProcessName; 
     var counter = new PerformanceCounter("Process", "Working Set - Private", prcName); 
     Console.WriteLine("{0}K", counter.RawValue/1024); 
     Console.ReadLine(); 
    } 
} 
+0

請注意雖然'Process.PrivateMemorySize64'訪問實際上是即時的,但創建性能計數器需要相​​當長的時間(秒),並且在需要高性能或實時報告的應用程序中可能不被接受。由於'Process'和'PerformanceCounter'是'IDisposable'的後代,所以你也必須用''using'換行。 – ajeh

相關問題