I am having an error when i try to display the current CPU and memory 开发者_Go百科usage using a progress bar. The code seems to be correct as it works with a label, but I am getting an error "Cannot convert to int" so how can I convert the performance counter's data into an int so it can be displayed in a progress bar? I tried using System.Convert.ToInt32(cpuCounter);
but it didn't work out for me. Here is my code:
PerformanceCounter ramCounter;
ramCounter = new PerformanceCounter("Memory", "Available MBytes");
ramCounter.NextValue();
progressBar1.Value = ramCounter;
PerformanceCounter cpuCounter;
cpuCounter = new PerformanceCounter();
cpuCounter.CategoryName = "Processor";
cpuCounter.CounterName = "% Processor Time";
cpuCounter.InstanceName = "_Total";
cpuCounter.NextValue();
progressBar2.Value = cpuCounter;
Thanks!
You need the result of PerformanceCounter.NextValue()
- you're currently ignoring it:
float value = cpuCounter.NextValue();
progressBar2.Value = (int) value;
You'll want to check the range of expected values of course - you may well want to scale it.
Another option is to use the RawValue
property, which is a long
.
You should not assign the Performance Counter instance to your progress bar but its value. The value itself is Int64.
progressbar1.Value = (Int32) ramCounter.RawValue;
Yours, Alois Kraus
精彩评论