简体   繁体   中英

Cross-thread operation not valid in parent control

I am using the following code to update a label in my class which extends UserControl :

private delegate void LabelChanger(bool signedIn);

public bool SignedIn
{
    get { return _signedIn; }
    set
    {
        _signedIn = value;
        labelChanger(value);
    }
}

private void labelChanger(bool signedIn)
{
    if (label1.InvokeRequired)
    {
        BeginInvoke(new LabelChanger(labelChanger), signedIn);
    }
    label1.Text = signedIn ? "Sign Out" : "Sign In";
}

The problem is that when the code gets to setting the label text, the UI is updated, however I get an `InvalidOperationException on a panel which is the label's parent. Any ideas why? Thanks.

The label1.Text = signedIn ? "Sign Out" : "Sign In"; label1.Text = signedIn ? "Sign Out" : "Sign In"; is executed even when you're in the wrong thread. You should enclose it with an else {} .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM