查看文章 |
一般来说,直接在子线程中对窗体上的控件操作是会出现异常,这是由于子线程和运行窗体的线程是不同的空间,因此想要在子线程来操作窗体上的控件,是不可能简单的通过控件对象名来操作,但不是说不能进行操作,微软提供了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; |