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

本文关键字:线程 控件 不能 其他 创建 一个 | 更新日期: 2023-09-27 17:58:04

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

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

有趣的是,我以前有一个应用程序,它有一个面板,我过去使用线程向它添加控件而没有任何问题,但这个应用程序不允许我这样做

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

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

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

您需要使用BeginInvoke从另一个线程安全地访问UI线程:

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

如果您试图从其他线程向父控件添加控件,则只能从创建父控件的线程向父控制添加控件

使用Invoke从另一个线程安全地访问UI线程:

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