Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cross-thread operation not valid when reading property

I am getting this error when I try to read a property from a custom panel control. The property returns the value of a textbox within the panel. How do I read the property that returns the value of the textbox control from another thread? Sample of my property code is below. I am not worried about the setter.

Here is the eaxct error message: Cross-thread operation not valid: Control '' accessed from a thread other than the thread it was created on.

public string Header
{
get
{
   return _HeaderComboBox.Text;
}
set
{
   _HeaderComboBox.Text = value;
}
}
like image 912
John Sheares Avatar asked Dec 17 '22 02:12

John Sheares


1 Answers

MSDN sample using BeginInvoke

This is how I would implement the sample based on the getter snippet you posted:

public string Header {
    get {
        string text = string.Empty;
        _HeaderComboBox.BeginInvoke(new MethodInvoker(delegate {
            text = _HeaderComboBox.Text;
        }));
        return text;
    }

    set {
        _HeaderComboBox.Text = value;
    }
}

There are more elegant methods, however, this is a general example for you.

like image 121
IAbstract Avatar answered Feb 04 '23 17:02

IAbstract