線程間操作無效: 從不是創建控件“...”的線程訪問它(解決方法)

1、在Form   Load事件中加入

System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls   =   false;
是最簡單的方式!

2、創建代理
delegate void SetTextCallback(string text);

創建和啓動線程
this .demoThread = 
               new Thread(new ThreadStart(this .ThreadProcUnsafe));
               this .demoThread.Start();

線程中要求改主窗體UI中的text屬性
private void ThreadProcSafe()
        {
           this .SetText("This text was set safely.");
        }

調用窗體中的函數用invoke傳遞參數
private void SetText(string text)
        {
            if (this .textBox1.InvokeRequired)
            {   
                SetTextCallback d = new SetTextCallback(SetText);
               this .Invoke(d, new object[] { text });
            }
           else
            {
               this .textBox1.Text = text;
            }

       }
 3、

{

1.定義 委託
  delegate   void  myDelegate( int  i);
   myDelegate mydelegate 
=   null ;

2.定義方法,顯示消息

public   void  ShowMessage( int  i)
        {
            
this .textBox1.Text  =  i.ToString();
            
this .progressBar1.Value  =  i;
        }



3.定義方法,驅動消息

public   void  MyEvent()
        {
            
for  ( int  i  =   0 ; i  <   100 ; i ++ )
            {
                Thread.Sleep(
100 );
                
this .BeginInvoke(mydelegate,  new   object [] {i});
            
            }
        }



4: 運行
 private   void  button1_Click( object  sender, EventArgs e)
        {
            mydelegate 
=   new  myDelegate(ShowMessage);
            Thread myThread 
=   new  Thread(MyEvent);

            
// IsBackground 是否後臺
            
// 這個屬性很重要 .如果 Thread IsBackground 等於false
            
//  當線程還沒有結束時,你點了關閉按鈕
            
//  將拋出An unhandled exception
            
// of type 'System.InvalidOperationException'
            
// occurred in System.Windows.Forms.dll 異常
            myThread.IsBackground  =   true ;
            myThread.Start();
        }

}

轉自 http://hi.baidu.com/lipan112000/blog/item/7f26d741ecc7d1029313c60d.html
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章