Zeynep Baran
Zeynep Baran

Reputation: 37

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

While writing a video converter program in c # form, I measure the convert speed with the progress bar. I am actually measuring using certain techniques, but I want to give the user how much CPU he uses with the actual values, that is, the speed of the process.

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

I did this with the code I found from inetnet, but I am failing. ro How can I fix?

In this pictures,

enter image description here

Upvotes: 0

Views: 294

Answers (1)

Clint
Clint

Reputation: 6509

First we initialize the the relevant CPU counters that you want to capture, and on ButtonClick we start to read the performance counter and increment the progress bar. The forloop and progressbar increments may not be relevant in your case but I added it to demonstrate the whole scenario

As per your clarification on comments section, this will update the textbox with the real time information from the 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());
    }

}


Note: Also Check Hans Passant's answer on ISupportInitialize

Upvotes: 1

Related Questions