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

问题描述 投票:0回答:1

[以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找到的代码来完成此操作,但是失败了。ro我该如何解决?

c# progress-bar performancecounter
1个回答
0
投票

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

根据您对评论的澄清,这将使用PerformanceCounters的实时信息更新文本框

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

}

注意:也请检查ISupportInitialize上Hans Passant的回答>

© www.soinside.com 2019 - 2024. All rights reserved.