为什么下面的代码报错:
    public partial class Form1 : Form
    {
        Thread t;        public Form1()
        {
            InitializeComponent();
        }        private void Form1_Load(object sender, EventArgs e)
        {        }        private void ThreadP()
        {
            textBox1.Text = "实现在子线程中操作主线程中的控件";
            t.Abort();
        }        private void button1_Click(object sender, EventArgs e)
        {
            t = new Thread(new ThreadStart(ThreadP));
            t.Start();
        }
    }----用下面的代码却可以:
    public partial class Form1 : Form
    {
        Thread t;
        private delegate void SetText();        public Form1()
        {
            InitializeComponent();
        }        private void Form1_Load(object sender, EventArgs e)
        {        }        private void ThreadP()
        {
            SetText d=new SetText(Threading);
            this.Invoke(d);
        }        private void Threading()
        {
            textBox1.Text = "实现在子线程中操作主线程中的控件";
            t.Abort();
        }        private void button1_Click(object sender, EventArgs e)
        {
            t = new Thread(new ThreadStart(ThreadP));
            t.Start();
        }
    }使用了delegate怎么就可以了呢?还有上面的"this",指的是窗体主线程吗?还是new 出来的那个线程呢?

解决方案 »

  1.   

    线程中不能直接操作UI上的控件,使用invoke通过代理可以实现
      

  2.   

    子线程  不能调用 主线程创建的 控件  必须 用 invoke 将控制权 转移给 主线程    用delegate 告诉 主线程该调用哪个方法 。然后运行   不知道您明白没  
      

  3.   

    为了保证线程安全,不能直接访问非本线程创建的控件,invoke则是类似消息队列的方式,可以保证线程安全
      

  4.   

    this.Invoke
    --------------
    这里的this指的是子线程?
      

  5.   

    你直接 看看this.ToString();
    不就知道this是啥了吗
      

  6.   

    噢,好象有点想明白了,
    因为:“子线程 不能调用 主线程创建的 控件”
    所以让窗体来Invoke调用线程的方法,
    而窗体要调用子线程的方法,就要用delegate的方式。就当就是这样理解吧?