0

I am having a bit of trouble putting two progress bars in the same tick event. The second progress bar either loads to 0% or 100% and nothing between these two values. This is the code i have so far.

        void timeElapsed(object sender, EventArgs e)
    {
        progressBar1.Value = (int)(power.BatteryLifePercent * 100);
        label1.Text = string.Format("{0}%", (power.BatteryLifePercent * 100));

        cpuCounter.CategoryName = "Processor";
        cpuCounter.CounterName = "% Processor Time";
        cpuCounter.InstanceName = "_Total";

        var unused = cpuCounter.NextValue();

        progressBar2.Value = (int)(cpuCounter.NextValue());
        label2.Text = "CPU  " + progressBar2.Value.ToString() + "%";
    }

The first progress bar loads fine and the battery percentage is correct however the second progress bar always is on 100% or 0%.

Sachin
  • 99
  • 1
  • 11

1 Answers1

0

You shouldn't read the counter 2 times in a row without waiting at least 1 second in between. If you remove your first call to cpuCounter.NextValue() in the method, everything should start working fine, otherwise the second call always returns 0 or 100, as I my testing has shown. As far as I can see, you don't use that value anywhere.

Change your method like this and it should work:

void timeElapsed(object sender, EventArgs e)
{
    progressBar1.Value = (int)(power.BatteryLifePercent * 100);
    label1.Text = string.Format("{0}%", (power.BatteryLifePercent * 100));

    cpuCounter.CategoryName = "Processor";
    cpuCounter.CounterName = "% Processor Time";
    cpuCounter.InstanceName = "_Total";

    //var unused = cpuCounter.NextValue();

    progressBar2.Value = (int)(cpuCounter.NextValue());
    label2.Text = "CPU  " + progressBar2.Value.ToString() + "%";
}

I got my infor from MSDN documentation:

If the calculated value of a counter depends on two counter reads, the first read operation returns 0.0. Resetting the performance counter properties to specify a different counter is equivalent to creating a new performance counter, and the first read operation using the new properties returns 0.0. The recommended delay time between calls to the NextValue method is one second, to allow the counter to perform the next incremental read.

As mentioned there, the very first call will still return 0.

Damir Arh
  • 17,637
  • 2
  • 45
  • 83