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

我知道还有 100 个这样的问题,但我似乎无法修复我的代码。我有一个返回控件的类,我想将此控件从 TabControl 添加到 Tabpage。我确定我在做一些迟钝的事情,而且我没有任何使用线程的经验。 如果我尝试修改这个example 它仍然不起作用。但如果我不修改它,它会在我的标签中添加一个标签。

private void RUN()
        {
            document = new TextDocument(inputFile);//fileName
            if (tabControl1.TabPages[0].InvokeRequired)
            {
                tabControl1.TabPages[0].BeginInvoke((MethodInvoker)delegate()
                {
                    System.Windows.Forms.Label l = new System.Windows.Forms.Label(); l.Location = new System.Drawing.Point(12, 10);
                    l.Text = "Some Text";
                    tabControl1.TabPages[0].Controls.Add(l);

                });//but if i have something like tabControl1.TabPages[0].Controls.Add(document.controls.content); i get an error
            }
        }

我也尝试过使用后台工作者,但也失败了。如果我不使用另一个线程它可以工作,但我需要在创建该控件时界面的其余部分工作(我从 xls 文件中读取并创建一个 ViewList,然后我将其添加到标签页)。

【问题讨论】:

    标签: c# multithreading winforms user-interface


    【解决方案1】:

    不知道问题是什么...

    这是一个在不同线程中创建但添加到主 UI 线程中的控件:

    public partial class Form1 : Form
    {
    
        public Form1()
        {
            InitializeComponent();
        }
    
        private void button1_Click(object sender, EventArgs e)
        {
            System.Threading.Thread T = new System.Threading.Thread(new System.Threading.ThreadStart(RUN));
            T.Start();
        }
    
        private void RUN()
        {
            // control created in a different thread:
            System.Windows.Forms.Label l = new System.Windows.Forms.Label();
            l.Location = new System.Drawing.Point(12, 10);
            l.Text = "Some Text";
    
            // control added in the main UI thread:
            if (tabControl1.TabPages[0].InvokeRequired)
            {
                tabControl1.TabPages[0].BeginInvoke((MethodInvoker)delegate()
                {        
                    tabControl1.TabPages[0].Controls.Add(l);
                });
            }
        }
    
    }
    

    【讨论】:

    • 我知道这个例子有效。但是当我在不同的类中创建我的控件并尝试将其添加到我的标签页时,我得到了跨线程错误。
    • document = new TextDocument(inputFile);此行创建一个新的 ListView 控件
    • 我对 TextDocument() 不熟悉...如何创建 ListView?上面的示例在不同的线程中创建了控件并且没有问题。这与返回它的不同类没有什么不同。请提供更多详细信息...
    • TextDocument() 它是我创建的一个类
    • 如果我不尝试使用线程/后台工作者,我只是创建列表视图,然后将其添加到标签页,它可以正常工作
    猜你喜欢
    • 2013-01-22
    • 1970-01-01
    • 1970-01-01
    • 2011-01-16
    • 2011-10-05
    • 2022-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多