C#子線程的控件操作問題解析
作者:曾洪寧
C#子線程直接操作控件會出現異常,因為子線程和運行窗體的線程是不同的空間。本文介紹如何通過Invoke方法實現C#子線程操作窗體上的控件。
有關C#子線程的控件操作
一般來說,直接在子線程中對窗體上的控件操作是會出現異常,這是由于子線程和運行窗體的線程是不同的空間,因此想要在子線程來操作窗體上的控件,是不可能簡單的通過控件對象名來操作,但不是說不能進行操作,微軟提供了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. C#子線程入口函數:
- /// < 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. 創建C#子線程:
- Thread thdProcess = new Thread( new ThreadStart( ThreadFun ) );
- thdProcess.Start();
備注:
- using System.Threading;
- private System.Windows.Forms.ProgressBar prgBar;
【編輯推薦】
責任編輯:yangsai
來源:
愚翁專欄