C# 如何获得特定的进程名内存使用率?

C# 如何获得特定的进程名内存使用率?,c#,winforms,performancecounter,C#,Winforms,Performancecounter,我尝试了以下代码: public static string GetProcessMemoryUsage(string processName) { while (true) { PerformanceCounter performanceCounter = new PerformanceCounter(); performanceCounter.CategoryNam

我尝试了以下代码:

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 差不多吧。而且在循环中我会一直得到更新。与任务管理器中的相同。

使用

var workingSet = (uint)performanceCounter.NextValue() / 1024;
return workingSet.ToString();
使用时,进程名称将被视为数字的格式字符串。因此,您有类似于
“Notepad.exe”
的格式字符串。它没有数字占位符,所以结果等于格式字符串值,即进程名称

注意-将内存使用率值分配给
processName
变量是非常容易混淆的。我建议使用此方法返回
uint
值:

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

甚至可以简单地使用来获取分配给进程的内存量。

Sergey以及我在哪里使用变量processName,或者如何使用变量processName?我的意思是如何获取特定进程名的uint?@user3681442将进程名作为性能计数器的实例名传递它正在工作,但如何在MB中显示它?我如何让它像在task manager中一样更频繁地更新?在task amanager中我看到198.5MB,而在method中我看到225340。(使用我使用的内容编辑了我的问题,而(true))@user3681442我回滚了您的编辑。问题应该简短且非常具体。你不应该在一个问题内写出整个程序。如果你有其他问题,问新问题。如果问题已回答,则将其标记为已接受。顺便说一句,以MBs为单位计算大小需要再除以1024。另外,如果您不希望得到四舍五入的结果,那么不要使用
uint
——让它成为浮点数。另一个注意事项-您的循环没有意义-您将在返回时退出此方法