C#跨线程操作控件

http://hi.baidu.com/xtzz/blog/item/65b21dd1afa5093b9b502780.html

C#跨线程操作控件    
         问题     
        因为我的C#程序全是在VS2005上作的,以前学VB.NET的时候机器上是有VS2003的,现在没有2003了,所以我提出的问题不知道VS2003上有没有,看了不少关于线程操作的文章,都没有找到满意的答案.
           错误请看代码:

              private void change()
        {
            this.label1.Text = "已发生变化";
        }
private void button1_Click(object sender, EventArgs e) //按钮事件
        {
            Thread cha = new Thread(new ThreadStart(change));
            cha.Start();
        }

            错误提示:

           未处理 System.InvalidOperationException
Message="线程间操作无效: 从不是创建控件“label1”的线程访问它。"
Source="System.Windows.Forms"
StackTrace:
       在 System.Windows.Forms.Control.get_Handle()
       在 System.Windows.Forms.Control.set_WindowText(String value)
       在 System.Windows.Forms.Control.set_Text(String value)
       在 System.Windows.Forms.Label.set_Text(String value)
       在 进程控件.Form1.change() 位置 C:\Documents and Settings\win.LEGEND-ECDE46B9\My Documents\Visual Studio 2005\Projects\进程控件\进程控件\Form1.cs:行号 15
       在 System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       在 System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       在 System.Threading.ThreadHelper.ThreadStart()
              无法跨线程操作,与创建控件的线程不一致
            解决方法:

private void change()
        {
            this.label1.Text = "已发生变化";
        }
private void threadchange()   //通过委托处理,MSDN上又很详细用法的说明
        {
            MethodInvoker In = new MethodInvoker(change);
            this.BeginInvoke(In);
        }
private void button1_Click(object sender, EventArgs e)
        {
            Thread cha = new Thread(new ThreadStart(threadchange));
            cha.Start();
        }

程序测试成功

posted on 2009-02-24 09:23  wmt  阅读(930)  评论(0编辑  收藏  举报

导航