【问题标题】:C# Controls created on one thread cannot be parented to a control on a different thread在一个线程上创建的 C# 控件不能作为另一个线程上的控件的父级
【发布时间】:2013-01-22 22:30:55
【问题描述】:

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

    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 线程修改 UI 元素。
  • 将业务内容(信息抓取)与 UI(创建标签)分开。
  • 为什么要创建线程只是为了添加 UI 元素?

标签: c# multithreading user-interface controls


【解决方案1】:

您不能从另一个线程更新 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);
            }
        }

【讨论】:

    【解决方案2】:

    您需要使用 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);
        }));
    

    【讨论】:

    • 无法使用错误 1:使用泛型类型 'System.Action' 需要 1 个类型参数
    【解决方案3】:

    您正在尝试从不同的线程将控件添加到父控件,控件只能从创建父控件的线程添加到父控件!

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

    【讨论】:

      猜你喜欢
      • 2013-06-27
      • 1970-01-01
      • 1970-01-01
      • 2011-01-16
      • 2011-10-05
      • 2022-11-21
      • 1970-01-01
      • 1970-01-01
      • 2015-04-24
      相关资源
      最近更新 更多