日期:2014-05-19  浏览次数:20638 次

一个线程的问题,在线等
初次接触线程
                private   void   button1_Click(object   sender,   EventArgs   e)
                {
                        TdFun();
                }

                private   void   TdFun()
                {
                        Thread   thread1   =   new   Thread(Fun1);
                        Thread   thread2   =   new   Thread(Fun2);

                        thread1.Start();
                        //Thread.Sleep(5000);
                        thread2.Start();
                }

                private   void   Fun1()
                {
                        textBox1.AppendText( "abc "   +   "\r\n ");
                        //MessageBox.Show( "fsad ");
                }

                private   void   Fun2()
                {
                        textBox2.AppendText( "def "   +   "\r\n ");
                        //MessageBox.Show( "eeeeeeee ");
                }

报如下错:
Cross-thread   operation   not   valid:   Control   'textBox1 '   accessed   from   a   thread   other   than   the   thread   it   was   created   on.


------解决方案--------------------
在VS05中,你不能在一个线程中访问另一个线程创建的的控件,如果你想访问,要使用MS所谓的对Windows窗体控件进行线程安全调用的方法(我菜,搞不懂这有什么安全不安全的)。你可以去下个中文的MSDN2005来看,在MSDN的地址是:ms-help://MS.VSCC.v80/MS.MSDN.v80/MS.VisualStudio.v80.chs/dv_fxmclictl/html/138f38b6-1099-4fd5-910c-390b41cbad35.htm 写得很详细。
当然你可以不用安全调用的方法,只要别在VS05中调试就行了,我一直用的不安全调用的方法(就是你这种方法),一直没出过问题。
------解决方案--------------------
这个是线程使用最常见的问题,错误原因是你在子线程里改变了主进程的资源,这是不允许的,因为textbox是主进程的资源。此时应该使用委托来通知主进程修改textbox的值
private void button1_Click(object sender, EventArgs e)
{
TdFun();
}

private void TdFun()
{
Thread thread1 = new Thread(Fun1);
//Thread thread2 = new Thread(Fun2);

thread1.Start();
//Thread.Sleep(5000);
//thread2.Start();
}

private void Fun1()
{
this.Invoke(new changetext(changetextinfo),new string[]{ "abc "});
}
delegate void changetext(string info);