【问题标题】:How do i get a specific process name memory usage?我如何获得特定的进程名称内存使用情况?
【发布时间】:2014-05-31 05:40:46
【问题描述】:

我试过这段代码:

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 类似的东西。并且它会在循环中一直得到更新。和任务管理器中的一样。

【问题讨论】:

    标签: c# winforms performancecounter


    【解决方案1】:

    使用

    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 来获取分配给进程的内存量。

    【讨论】:

    • Sergey 我在哪里使用或如何使用变量 processName ?我的意思是如何获取特定进程名称的 uint?
    • @user3681442 传递进程名称作为性能计数器的实例名称
    • Sergey 它正在工作,但我如何在 MB 中显示它?以及如何使它像在任务管理器中那样更频繁地更新?在任务管理器中我看到 198.5MB 而在方法中我看到 225340 。 (编辑了我的问题,我使用了 while(true))
    • @user3681442 我回滚了您的编辑。问题应该简短且非常具体。您不应该在一个问题中编写整个程序。如果您有其他问题,请提出新问题。如果问题得到回答,则将其标记为已接受。顺便说一句,以 MB 为单位计算大小需要再除以 1024。此外,如果您不想要四舍五入的结果,请不要使用 uint - 让它成为浮点数。另一个注意事项-您的循环没有意义-您将在返回时退出此方法
    猜你喜欢
    • 2013-04-25
    • 1970-01-01
    • 1970-01-01
    • 2010-10-24
    • 2013-09-16
    • 2017-05-03
    • 1970-01-01
    • 2023-03-27
    相关资源
    最近更新 更多