I currently use this code to get the usage value of the four cores in my CPU, and display each one to their own label:
string[] cpuUsage = new string[100];
int i = 0;
//Get CPU usage values using WMI
ManagementObjectSearcher searcher = new ManagementObjectSearcher("select * from Win32_PerfFormattedData_PerfOS_Processor");
foreach (ManagementObject obj in searcher.Get())
{
cpuUsage[i] = obj["PercentProcessorTime"].ToString();
i++;
}
LA_Core1.Content = "Core usage: " + cpuUsage[0] + "%";
LA_Core2.Content = "Core usage: " + cpuUsage[1] + "%";
LA_Core3.Content = "Core usage: " + cpuUsage[2] + "%";
LA_Core4.Content = "Core usage: " + cpuUsage[3] + "%";
However, for the first time that this code is run, it freezes up my program for around 10 seconds before finally displaying the value. Past this first time, however, the code runs near instantly. What exactly is happening here to make it so slow on the first run, but not on any subsequent run?
When you use WMI to query something on the computer, it will execute that query and will not do anything until it returns the results. To prevent this, you could utilize multithreading so you can run the query without locking your program from anything else.
As for the time to execute the query, which happens to me sometimes, I can only assume that local machine caches results to a degree. So, subsequent searches will be quicker. You might also notice that if you close the program and re-test the operations time, the cache will be flushed so the first query will take a long time again.