C#后台进程cpu负载使用PerformanceCounter
Posted
技术标签:
【中文标题】C#后台进程cpu负载使用PerformanceCounter【英文标题】:C# Background process cpu load using PerformanceCounter 【发布时间】:2016-09-15 08:19:15 【问题描述】:我正在尝试为后台进程获取 CPU 负载; Background process
使用性能计数器
PerformanceCounter ramCounter = new PerformanceCounter("Process", "Working Set", process.ProcessName);
PerformanceCounter cpuCounter = new PerformanceCounter("Process", "% Processor Time", process.ProcessName);
ramCounter.NextValue();
cpuCounter.NextValue();
while (true)
Thread.Sleep(500);
double ram = ramCounter.NextValue();
double cpu = cpuCounter.NextValue();
Console.WriteLine("RAM: " + (ram / 1024 / 1024) + " MB; CPU: " + (cpu) + " %");
它在(应用程序)上表现不错,但在 Backgorund 每次都返回 0 时失败; 我很困惑; 为这些进程检索 CPU 负载的正确方法是什么?
【问题讨论】:
检查这个例子。 codeproject.com/Articles/10258/… 该进程的多个实例处于活动状态,它们都具有相同的名称。那么您实际监控的是哪一个? ***.com/a/9115662/17034 我正在运行 throw 所有这些,结果是相同的 0 cpu 负载; ` List实际上,Hans Passant 给了我一个很好的暗示; 所以问题不在于后台进程,而在于有多个具有相同 ProcessName 的实例。 因此,为了创建性能计数器,您应该通过进程 id 获取进程实例名称,换句话说:
string processNameYourAreLookingFor ="name";
List<Process> prc_Aspx = runningNow.Where(x => x.ProcessName == processNameYourAreLookingFor ).ToList();
foreach (Process process in prc_Aspx)
string _prcName = GetProcessInstanceName(process.Id);
new PerformanceCounter("Process", "% Processor Time", _prcName);
还有 GetProcessInstanceName by id
private string GetProcessInstanceName(int pid)
PerformanceCounterCategory cat = new PerformanceCounterCategory("Process");
string[] instances = cat.GetInstanceNames();
foreach (string instance in instances)
using (PerformanceCounter cnt = new PerformanceCounter("Process",
"ID Process", instance, true))
int val = (int)cnt.RawValue;
if (val == pid)
return instance;
throw new Exception("Could not find performance counter " +
"instance name for current process. This is truly strange ...");
【讨论】:
以上是关于C#后台进程cpu负载使用PerformanceCounter的主要内容,如果未能解决你的问题,请参考以下文章