Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

update a control in UI with running background Thread in Winforms

I am using Background Worker Thread in my Winform, inside my Do_Work Event I am calculating something, what I need the thing is that simultaneously I would like to update a label which is in main/UI thread ? how to achieve this?

I want to update my label from Do_Work event...

like image 945
yogendra Avatar asked Oct 19 '25 05:10

yogendra


2 Answers

In WinForms (WPF as well) UI controls can only be updated in the UI thread. You should update your label this way:

public void UpdateLabel(String text){
    if (label.InvokeRequired)
    {
        label.Invoke(new Action<string>(UpdateLabel), text);
        return;
    }      
    label.Text = text;
}
like image 96
GETah Avatar answered Oct 21 '25 20:10

GETah


Inside your Do_Work method, you can use the object's Invoke() method to execute a delegate on its UI thread, e.g.:

this.Invoke(new Action<string>(UpdateLabel), newValue);

...and then make sure to add a method like this to your class:

private void UpdateLabel(string value)
{
    this.lblMyLabel.Text = value;
}
like image 26
Jon Avatar answered Oct 21 '25 18:10

Jon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!