Refresh the label without crashing the program

3

I need to update my label at all times when I use timer it updates, but it crashes the program

Program.cs

public static String Uso()
{

    ManagementClass mc = new ManagementClass("win32_processor");
    ManagementObjectCollection moc = mc.GetInstances();
    String Id = String.Empty;
    foreach (ManagementObject mo in moc)
    {
        Id = mo.Properties["LoadPercentage"].Value.ToString();
        break;
    }

    return Id;
}

Form1.cs

private void timer1_Tick(object sender, EventArgs e)
{
    label42.Text = Program.HardwareInfo.Uso();
}

I can not find a way to update the processor usage information and let my program run normally.

    
asked by anonymous 11.11.2015 / 18:04

2 answers

3

This must be happening because the timer interval ( timer.Interval ) is too short and the main thread is always locked running the timer event.

You can do this in a thread by only exchanging the timer you're using ( System.Windows.Forms.Timer ) to an System.Timers.Timer .

This should work for you. Note that the event is now Elapsed and not the Tick

public timer_Elapsed(Object source, ElapsedEventArgs e){
    this.Invoke(new MethodInvoker(() => label42.Text = Program.HardwareInfo.Uso()));
}

There are other things that I improve on, maybe even use a timer. But that should be enough to solve your problem without messing around in the code.

    
11.11.2015 / 18:20
3

There's nothing wrong with what you're doing. At least not in the stretch shown. The Timer setting may be wrong. Make sure you're seeing the example in documentation .

The timer is the correct one for Windows Forms. There is no reason to use thread there. Not even asynchrony seems adequate. The function of timer is to call the established method. If it runs fast, and this type of task must run very fast, otherwise it is unfeasible, everything will work almost without realizing it. Any mechanism trying to use thread would only make the situation worse.

Maybe any form is locking the application. That's another problem. In fact it is a problem of what is running the most, because the form is sovereign and it must allow other parts to run freely. But I'm just speculating, since there are no details in the question.

I would just change the way it captures information. I would not use WMI. I would create a property on the form to hold a Windows performance counter:

private PerformanceCounter cpuCounter = 
          new PerformanceCounter("Processor", "% Processor Time", "_Total"); 

And then there would be:

private void timer1_Tick(object sender, EventArgs e) {
    label42.Text = cpuCounter.NextValue().ToString();
}

You may need to tailor what you need, but the basis is that.

    
11.11.2015 / 19:06