如何获取特定的进程名称内存使用情况?

时间:2014-05-30 21:08:07

标签: c# winforms performancecounter

我试过这段代码:

public static string GetProcessMemoryUsage(string processName)
        {
            while (true)
            {
                PerformanceCounter performanceCounter = new PerformanceCounter();
                performanceCounter.CategoryName = "Process";
                performanceCounter.CounterName = "Working Set";
                performanceCounter.InstanceName = Process.GetCurrentProcess().ProcessName;
                processName = ((uint)performanceCounter.NextValue() / 1024).ToString(processName);
                return processName;
            }
        }

如果进程名称是例如:BFBC2Game 然后方法GetProcessMemoryUsage只返回名称:BFBC2Game 我希望它返回内存使用值数字,如在Windows中的任务管理器中,例如当我运行任务管理器时,我在BFBC2Game上看到:78%和198.5MB内存使用情况。

这就是我想要在返回的字符串processName中获得的内容:78%和198.5MB 这样的事情。而且它会在循环中一直得到更新。与任务管理器中的相同。

1 个答案:

答案 0 :(得分:3)

使用

var workingSet = (uint)performanceCounter.NextValue() / 1024;
return workingSet.ToString();

使用UInt32.ToString(processName)时,进程名称将被视为数字的格式字符串。所以,你有像"Notepad.exe"这样的格式字符串。它没有数字的占位符,因此结果等于格式化字符串值,即进程名称。

注意 - 将内存使用价值分配给processName变量非常令人困惑。我建议从此方法返回uint值:

public static uint GetProcessMemoryUsageInKilobytes(string processName)
{
    var performanceCounter = 
        new PerformanceCounter("Process", "Working Set", processName);
    return (uint)performanceCounter.NextValue() / 1024;
}

甚至只需使用Process.WorkingSet64来获取分配给处理的内存量。

相关问题