It's okay, because NextValue always return 0 when you call it first time.
For fix this error you can call NextValue function twice after creation PerformanceCounter object (durty hack).
Question
I'm trying to get the CPU usage of a specific process, but it returns just 0. I still don't know what the problem is.
Process[] processlist = Process.GetProcesses();
foreach (Process theprocess in processlist)
{
if (GetProcessOwner(theprocess.Id) != "NO_OWNER")
{
if (theprocess.ProcessName != "svchost")
{
var ram = BytesToString(theprocess.PeakWorkingSet64);
ram = ram.Replace("MB", "");
string state = "";
if (theprocess.MainWindowTitle == "")
{
state = "background";
}
else
{
state = "foreground";
}
sw.WriteLine("ID=" + theprocess.Id + "&NAME=" + theprocess.ProcessName + "&RAM=" + ram + "&STARTED=" + theprocess.StartTime + "&STATE=" + state);
PerformanceCounter counter = new PerformanceCounter("Process", "% Processor Time", theprocess.ProcessName);
Console.WriteLine("CPU="+counter.NextValue());
}
}
}
Solution
It's okay, because NextValue always return 0 when you call it first time.
For fix this error you can call NextValue function twice after creation PerformanceCounter object (durty hack).