在一个线程上创建的C#控件不能作为另一个线程上的控件的父级

在一个线程上创建的C#控件不能作为另一个线程上的控件的父级

问题描述:

我正在运行一个线程,该线程获取信息并创建标签并显示它,这是我的代码

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.

您不能从另一个线程更新UI线程:

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);
            }
        }