views:

509

answers:

2

Hello,

How do I calculate the private working set of memory using C#? I'm interested in produces roughly the same figure as taskmgr.exe.

I'm using the Process namespace and using methods/data like WorkingSet64 and PrivateMemorySize64, but these figures are off by 100MB or more at times.

Thanks,

A: 

Maybe http://msdn.microsoft.com/en-us/library/system.gc.gettotalmemory.aspx will provide data you need?

Tomas Voracek
+3  A: 

This is a highly variable number, you cannot calculate it. The Windows memory manager constantly swaps page in and out of RAM. TaskMgr.exe gets it from a performance counter. You can get the same number like this:

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();
    }
}

Do beware that the number really doesn't mean much, it will drop when other processes get started and compete for RAM.

Hans Passant
How do you mean that, "the number really doesn't mean much"? Doesn't this figure represent how much memory the process uses that cannot be shared with another process?I'm interested in building a service that will kill process "abusive" processes - "abusive" being defined as processes using more than x many MB of memory. I would hate to write the service if the figure I'm using really doesn't mean much.What would you suggest?
sholsapp
No, that's not what the number means. You are looking for "Private Bytes", the amount of *virtual* memory taken by a process that can't be shared by other processes.
Hans Passant
While all being said is correct, I wanted to add, that just using the `ProcessName` to lookup the matching counter instance is not enough. If you have multiple processes with the same (e.g. svchost.exe) then the counter names will be "svchost#1", "svchost#2", etc. You need to match via the "ID Process" counter, which is also part of the process category, and `Process.ID`.
Christian.K