下面是一个窗体程序代码,一个按钮,一个label。为什么一调试就报错:下面所示线程间操作无效: 从不是创建控件“label1”的线程访问它。不调试没错,匿名委托应该能访问包含它的类变量的啊!
        private void button1_Click(object sender, EventArgs e)
        {
            new System.Threading.Thread(delegate()
            {
                this.label1.Text = "1";                System.Threading.Thread.Sleep(5000);                this.label1.Text = "2";
            })
            .Start();
        }

解决方案 »

  1.   

            private void button1_Click(object sender, EventArgs e)
            {
                new System.Threading.Thread(delegate()
                {
                    this.Invoke(new MethodInvoke(delegate
                    {
                  
                    this.label1.Text = "1";                System.Threading.Thread.Sleep(5000);                this.label1.Text = "2";
                    }));
                })
                .Start();
            }
      

  2.   

    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 WindowsApplication1
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();        }
            private void button1_Click(object sender, EventArgs e)
            {
                new System.Threading.Thread(delegate()
                {
                    this.Invoke(new MethodInvoker(delegate
                     {                     this.label1.Text = "1";                     System.Threading.Thread.Sleep(5000);                     this.label1.Text = "2";
                     }));
                })
                .Start();         }    }
    }