1. 程式人生 > >執行緒間操作無效: 從不是建立控制元件“progressBar1”的執行緒訪問它

執行緒間操作無效: 從不是建立控制元件“progressBar1”的執行緒訪問它

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.定義 委託
   delegatevoid myDelegate(int i);
   myDelegate mydelegate 
=null;

2.定義方法,顯示訊息

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



3.定義方法,驅動訊息

publicvoid MyEvent()
        {
            
for

 (int i =0; i <100; i++)
            {
                Thread.Sleep(
100);
                
this.BeginInvoke(mydelegate, newobject[] {i});
            
            }
        }



4: 執行
  privatevoid 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();
        }

}