C# Controls created on one thread cannot be parent

2019-02-17 22:06发布

问题:

I am running a thread and that thread grabs information and create labels and display it, here is my code

    private void RUN()
    {
        Label l = new Label();
        l.Location = new Point(12, 10);
        l.Text = "Some Text";
        this.Controls.Add(l);
    }

    private void button1_Click(object sender, EventArgs e)
    {
        Thread t = new Thread(new ThreadStart(RUN));
        t.Start();
    }

The funny thing is that i had a previous application that has a panel and i used to add controls to it using threads without any issue, but this one won't let me do it.

回答1:

You cannot update UI thread from another thread:

 private void RUN()
        {
            if (this.InvokeRequired)
            {
                this.BeginInvoke((MethodInvoker)delegate()
                {
                    Label l = new Label(); l.Location = new Point(12, 10);
                    l.Text = "Some Text";
                    this.Controls.Add(l);
                });
            }
            else
            {
                Label l = new Label();
                l.Location = new Point(12, 10);
                l.Text = "Some Text";
                this.Controls.Add(l);
            }
        }


回答2:

You need to use BeginInvoke to access the UI thread safely from another thread:

    Label l = new Label();
    l.Location = new Point(12, 10);
    l.Text = "Some Text";
    this.BeginInvoke((Action)(() =>
    {
        //perform on the UI thread
        this.Controls.Add(l);
    }));


回答3:

Your are trying to add control to a parent control from a different thread , controls can be added to parent control only from the thread parent control was created!

use Invoke to access the UI thread safely from another thread:

    Label l = new Label();
    l.Location = new Point(12, 10);
    l.Text = "Some Text";
    this.Invoke((MethodInvoker)delegate
    {
        //perform on the UI thread
        this.Controls.Add(l);
    });