C#后台进程CPU负载使用PerformanceCounter
问题描述:
我想获得CPU负载的后台进程; Background processC#后台进程CPU负载使用PerformanceCounter
使用性能计数器
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) + " %");
}
它确实相当不错的软件(Apps),但却未能在Backgorund返回每次0; 我很困惑; 什么是正确的方式来检索CPU类型的过程?
答
其实汉斯帕斯特给了我一个很好的提示; 所以这个问题不是在后台进程中,而是在具有相同ProcessName的多个实例。 所以为了创建性能计数器,你应该通过进程ID换句话说获得流程实例名,由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 ...");
}
检查这个例子
而且GetProcessInstanceName。 http://www.codeproject.com/Articles/10258/How-to-get-CPU-usage-of-processes-and-threads – active92
该进程有几个活动实例,都具有相同的名称。那么你究竟在监视哪一个? http://*.com/a/9115662/17034 –
我正在运行抛出所有这些,结果是相同的0 cpu负载; 'List prc = runningNow.Where(x => x.ProcessName == txtApp.Text).ToList(); foreach(处理过程在prc中) {..' –
MultyPulty