I'm just trying to get the exact CPU usage that matches the task manager. So far I have tried four recommended methods that do not work.
Firstly, I tried similar solutions or suggestions that I could find. The code sample uses four methods, all of which are inaccurate. Secondly, I know that the task manager fluctuates and depends on when it is selected. This still does not explain the difference. Finally, I know that there are different methods, and that the task manager uses only one method. Since this is intended for ordinary users, it should be close to the task manager.
public partial class MainWindow : Window
{
PerformanceCounter cpuCounterPi = new PerformanceCounter("Processor Information", "% Processor Time", "_Total");
PerformanceCounter cpuCounterP = new PerformanceCounter("Processor", "% Processor Time", "_Total");
ManagementObjectSearcher query1 = new ManagementObjectSearcher("select loadpercentage from win32_processor");
CounterSample csPi1, csPi2, csP1, csP2;
double cpuPercentagePi, cpuPercentageP, cpuPercentageLoad;
int count = -1;
Boolean alternate = false;
System.Windows.Threading.DispatcherTimer dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
public MainWindow()
{
InitializeComponent();
dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
dispatcherTimer.Interval = new TimeSpan(0, 0, 5);
dispatcherTimer.Start();
}
private void dispatcherTimer_Tick(object sender, EventArgs e)
{
count++;
if (alternate)
{
csPi1 = cpuCounterPi.NextSample();
cpuPercentagePi = CounterSample.Calculate(csPi2, csPi1);
csP1 = cpuCounterP.NextSample();
cpuPercentageP = CounterSample.Calculate(csP2, csP1);
}
else
{
csPi2 = cpuCounterPi.NextSample();
cpuPercentagePi = CounterSample.Calculate(csPi1, csPi2);
csP2 = cpuCounterP.NextSample();
cpuPercentageP = CounterSample.Calculate(csP1, csP2);
}
alternate = !alternate;
if (count==5) { textBox.Clear(); count = 0; }
textBox.Text = textBox.Text + "\nProcessor Information (Method 1) " + cpuPercentagePi.ToString();
textBox.Text = textBox.Text + "\nProcessor (Method 2) " + cpuPercentageP.ToString();
textBox.Text = textBox.Text + "\nProcessor ½ (Method 2 divided by 2) " + (cpuPercentageP/2).ToString();
ManagementObjectCollection cpuColl = query1.Get();
foreach (ManagementObject mo in cpuColl)
{
cpuPercentageLoad = Convert.ToDouble(mo["loadpercentage"]);
}
textBox.Text = textBox.Text + "\nProcessor Load (Method 3) " + cpuPercentageLoad.ToString() + "\n";
}
Here are two examples of comparison with the task manager.

, . - Intel Skylake i7-6650U, Windows 10.
- :
PerformanceCounter , ,
#?
Windows?