百度空间 | 百度首页 
 
查看文章
 
如何在子线程中操作窗体上的控件
2008-06-18 18:18

一般来说,直接在子线程中对窗体上的控件操作是会出现异常,这是由于子线程和运行窗体的线程是不同的空间,因此想要在子线程来操作窗体上的控件,是不可能简单的通过控件对象名来操作,但不是说不能进行操作,微软提供了Invoke的方法,其作用就是让子线程告诉窗体线程来完成相应的控件操作。

现在用一个用线程控制的进程条来说明,大致的步骤如下:

1. 创建Invoke函数,大致如下:

        /// <summary>

        /// Delegate function to be invoked by main thread

        /// </summary>

        private void InvokeFun()

        {

            if( prgBar.Value < 100 )

                prgBar.Value = prgBar.Value + 1;

        }

2. 子线程入口函数:

        /// <summary>

        /// Thread function interface

        /// </summary>

        private void ThreadFun()

        {

            //Create invoke method by specific function

            MethodInvoker mi = new MethodInvoker( this.InvokeFun );

            for( int i = 0; i < 100; i++ )

            {

                this.BeginInvoke( mi );

                Thread.Sleep( 100 );

            }

        }

3. 创建子线程:

            Thread thdProcess = new Thread( new ThreadStart( ThreadFun ) );

            thdProcess.Start();

       备注:

              using System.Threading;

              private System.Windows.Forms.ProgressBar prgBar;


类别:c# | 添加到搜藏 | 浏览() | 评论 (1)
 
最近读者:
 
网友评论:
2
2009-02-11 20:08 | 回复
1111111
 
发表评论:
姓 名:
网址或邮箱: (选填)
内 容:
验证码: 请点击后输入四位验证码,字母不区分大小写
      

     

©2009 Baidu