我在网上看到一个给线程传递参数的例子(http://crazywill.cnblogs.com/archive/2005/08/25/222579.aspx),我试着做了,但是线程在调用myCallback函数时,对界面控件的操作产生异常,执行label1.Text = i.ToString();  时报“Cross-thread operation not valid: Control 'label1' accessed from a thread other than the thread it was created on.”
为什么对label1,progressBar1的操作会产生错误我写的代码如下
namespace ThreadTest
{
    public delegate void ThreadCallback(int i);
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }        private void button1_Click(object sender, EventArgs e)
        {
            const int Max = 800001;
            progressBar1.Maximum = Max;
            progressBar1.Value = 0;
            myThreadClass myThread = new myThreadClass(Max, new   ThreadCallback(myCallback));
            Thread t = new Thread(new ThreadStart(myThread.myRun));
            t.Start();
            
        }
 
        public void myCallback(int i)
        {
            label1.Text = i.ToString();
            label1.Refresh();
            progressBar1.Value = i;
            progressBar1.Refresh();
        }    }    class myThreadClass
    {
        private int Max = 0;
        private ThreadCallback callback;
        public myThreadClass(int initValue, ThreadCallback callbackDelegate)
        {
            Max = initValue;
            callback = callbackDelegate;
        }
        public void myRun()
        {
            for (int i = 0; i < 1000000; i++)
            {
                if (i % 1000 == 0)
                {
                    if (callback != null)
                    {
                        callback(i);                    }
                }            }
        }    }}

解决方案 »

  1.   

    public void myCallback(int i)
            {
    if  (this.invokerequied)
    {
    ThreadCallback d = new ThreadCallback(myCallback);
                    this.Invoke(d, new object[] { i });
    }
    esle
    {
                label1.Text = i.ToString();
                label1.Refresh();
                progressBar1.Value = i;
                progressBar1.Refresh();
    }
            }  
    *****************************************************************************
    欢迎使用CSDN论坛专用阅读器 : CSDN Reader(附全部源代码) 最新版本:20070130http://www.cnblogs.com/feiyun0112/archive/2006/09/20/509783.html