using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;namespace Test
{
    public partial class Form1 : Form
    {
        private Thread thread;
        public Form1()
        {
            InitializeComponent();
            thread = new Thread(new ThreadStart(Add));
            thread.Start();
        }        private void Add()
        {
            Label label = new Label();
            label.Text = "test";
            label.Location=new Point(50,50);
            this.Controls.Add(label);      //执行这句时,会抛出异常InvalidOperationException
                                           //线程间操作无效: 从不是创建控件“Form1”的线程访问它。
        }        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            thread.Abort();
        }
    }
}请大家帮忙看看吧,在线程中动态的添加控件该怎么写?贴段代码来看看 非常感谢

解决方案 »

  1.   

    BackgroundWorker 在线程中的某一时间点发送消息到主线程,由主线程加控件
      

  2.   

    由于你添加控件是由线程来操作的不是由主线程调用,微软为了防止线程死锁,
    所以需要一个委托方法来实现控件添加的动作
    方法1: Control.CheckForIllegalCrossThreadCalls = false 暂时关闭安全检测
    方法2:微软说这是最安全的方法,其实线程死锁是不可避免的 
    private delegate void AddCallback();
    private void Add() 

      if (this.textBox1.InvokeRequired) 
      { 
        AddCallback d = new AddCallback (); 
        this.Invoke(d, new object[] {}); 
      } 
      else 
      { 
         Label label = new Label();
         label.Text = "test";
         label.Location=new Point(50,50);
         this.Controls.Add(label);      
      } 
    }哪个顺眼,选哪个把
      

  3.   

            private void Add()
            {
                Label label = new Label();
                label.Text = "test";
                label.Location = new Point(50, 50);
                //this.Controls.Add(label);      
                AddLabel(label);
            }        delegate void AddLabelHandle(Label label);
            private void AddLabel(Label label)
            {
                if (this.InvokeRequired)
                {
                    AddLabelHandle method = new AddLabelHandle(AddLabel);
                    this.Invoke(method, label);
                }
                else
                {
                    this.Controls.Add(label);
                }
            }
      

  4.   


            private delegate void AddDelegate();
            Thread thread ;        private void Form1()
            {
                thread = new Thread(new ThreadStart(threadtemp));
                thread.Start();
            }
            private void threadtemp()
            {
                AddDelegate addm = new AddDelegate(Add);
                this.Invoke(addm, new object[] { });
            }
            private void Add()
            {
                Label label = new Label();
                label.Text = "test";
                label.Location = new Point(10, 10);
                this.Controls.Add(label);      
            }