如何在 C# 中将两个进度条放在同一个 tick 事件中

How can put two progress bars in the same tick event in c#

我在将两个进度条放在同一个滴答事件中时遇到了一些麻烦。第二个进度条加载到 0% 或 100%,这两个值之间没有任何内容。这是我目前的代码。

        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() + "%";
    }

第一个进度条加载正常,电池百分比正确,但第二个进度条始终为 100% 或 0%。

你不应该连续读取计数器 2 次而中间至少等待 1 秒。如果您在方法中删除对 cpuCounter.NextValue() 的第一次调用,一切都应该开始正常工作,否则第二次调用总是 returns 0 或 100,正如我的测试所示。据我所知,您不会在任何地方使用该值。

像这样改变你的方法,它应该有效:

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() + "%";
}

我的信息来自 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.

正如那里提到的那样,第一个电话仍然 return 0.