如何在不使用 C# 形式的计时器的情况下使用性能计数器?我收到类似未找到类别名称的错误

How can I use performance counter without using a timer in c # form? I get an error like Category name is not found

在写一个c#格式的视频转换程序时,我用进度条来衡量转换速度。我实际上是在使用某些技术进行测量,但是我想用实际值给用户CPU他使用了多少,即过程的速度。

if (comboBox1.Text == "mp3")
                {
                  var convert = new NReco.VideoConverter.FFMpegConverter();
                    convert.ConvertMedia(VideoPath, MusicPath, "mp3");
                    progressBar1.Value = (int)(performanceCounter1.NextValue());
                    label7.Text = "Processor Time: " + progressBar1.Value.ToString() + "%";
                    /*   progressBar1.Value = 80;
                        label7.Text = "% 80";*/
                    MessageBox.Show("converst is okey");
                    progressBar1.Value = (int)(performanceCounter1.NextValue());
                    label7.Text = "Processor Time: " + progressBar1.Value.ToString() + "%";

我用从 inetnet 找到的代码做了这个,但我失败了。 我该如何解决?

在这张照片中,

首先我们初始化您要捕获的相关 CPU 计数器,然后在 ButtonClick 我们开始读取性能计数器并递增进度条。 forloopprogressbar 增量可能与您的情况无关,但我添加它是为了演示整个场景

根据您在评论部分的说明,这将使用来自性能计数器的实时信息更新文本框

public PerformanceCounter privateBytes;
public PerformanceCounter gen2Collections;
public Form1()
{

    InitializeComponent();

    var currentProcess = Process.GetCurrentProcess().ProcessName;
    privateBytes =  new PerformanceCounter(categoryName: "Process", counterName: "Private Bytes", instanceName: currentProcess);
    gen2Collections = new PerformanceCounter(categoryName: ".NET CLR Memory", counterName: "# Gen 2 Collections", instanceName: currentProcess);

}
async Task LongRunningProcess()
{

    await Task.Delay(500);

}
private async void button1_Click(object sender, EventArgs e)
{

    for (int i = 0; i <100; i++)
    {
        progressBar1.Value = i;
        textBox1.Text = "privateBytes:" + privateBytes.NextValue().ToString() + " gen2Collections:" + gen2Collections.NextValue().ToString() ;
        await Task.Run(() => LongRunningProcess());
    }

}


注意:另请查看 Hans Passant 在 ISupportInitialize

上的回答