I have been trying to get the total CPU usage of windows PC (Windows 7 running .Net 4.5) in C#. It looks like using PerformanceCounter should be able to meet my needs.
I wrote some trial code based off the three links below (and checking the msdn pages), this was the most basic version:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
namespace EntropyProject
{
class Program
{
static void Main(string[] args)
{
PerformanceCounter cpuCounter;
cpuCounter = new PerformanceCounter();
cpuCounter.CategoryName = "Processor";
cpuCounter.CounterName = "% Processor Time";
cpuCounter.InstanceName = "_Total";
while(true)
{
try
{
float firstValue = cpuCounter.NextValue();
System.Threading.Thread.Sleep(500);
Console.WriteLine("Before getting processor:");
float currentCpuUsage = cpuCounter.NextValue();
Console.WriteLine("After getting processor:");
System.Threading.Thread.Sleep(1000);
Console.WriteLine(currentCpuUsage);
}
catch (Exception e)
{
Console.WriteLine("\n{0}\n", e.Message);
}
System.Threading.Thread.Sleep(10000);
}
}
}
}
Whenever NextValue is called the exception error below is triggered. This appears to be a common problem with an issue with performance counter values.
Cannot load Counter Name data because an invalid index '' was read from registry
Most recommended solutions suggest that you rebuild the corrupted items using lodctr in a raised command window as admin. However I was wanting to use the PerformanceCounters in a program which would be released to a large number of people and so would be inappropriate to expect them to rebuild their PerformanceCounters using the command window.
Questions:
- Why is this exception error occurring?
- How do you properly use PerformanceCounter otherwise?
- How can I avoid getting my programs users to have to open a cmd window and rebuild their performance counters?
Sources:
How to get cpu usage in C
Get current cpu utilisation in
How can I get the total CPU usage?
Similar Question about error when accessing counter name asked by Annie Sheikh