I am trying to get overall CPU usage of a Windows PC (Windows 7 running .Net 4.5) in C #. It seems like using PerformanceCounter should meet my needs.
I wrote some trial code based on the three links below (and checking the msdn pages), it was the simplest 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 exception below is raised. This is apparently a common problem with the performance counter performance issue.
Cannot load counter data because an invalid index was read '' from the registry
The most recommended solutions suggest that you repair damaged items using lodctr in a raised command window as an administrator. However, I wanted to use PerformanceCounters in a program that would be released to a large number of people, and so it would be inappropriate to expect them to rebuild their PerformanceCounters using the command window.
Questions:
- Why does this exception error occur?
- How to use PerformanceCounter correctly otherwise?
- How can I avoid users of my programs having to open the cmd window and rebuild their performance counters?
Sources:
A similar error message when accessing the counter name asked by Annie Sheikh
c # performancecounter cpu-usage
Luke
source share