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());
        }
    }
}
Was it helpful?

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).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top