首先說下,.net 2.0以后加強了安全機制,不允許在winform中直接跨線程訪問控件的屬性。所以除了控件所在的線程外的線程調用會拋異常
(Cross-thread operation not valid:Control 'textBox1' accessed from a thread other than the thread it was created on .)
下面進入正題:
第一種方法:
public DomainQuery2() { InitializeComponent(); System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false;//設置該屬性 為false }
這種方法很方便,但是會有安全問題。
第二種方法:
private delegate void FlushClient(string a); //代理委托 //代理賦值方法 private void TextboxFZ3(string str) { if (this.textBox3.InvokeRequired) { FlushClient fc = new FlushClient(TextboxFZ3); this.Invoke(fc, str); //通過代理調用刷新方法 } else { this.textBox3.AppendText(str + "\r\n"); } } //這個就是要開啟線程的方法 如果要操作控件,必須調用上面的方法 private void FZ(object obj) { TextboxFZ3(obj); } //點擊執行 private void button1_Click(object sender, EventArgs e) { Thread thread = new Thread(new ParameterizedThreadStart(SerchInfo)); thread.IsBackground = true; thread.Start(“我是子線程操作的控件賦值”); }
我喜歡先上代碼然后解釋,第一句:代理委托,當要操作控件的時候做一個判斷,如果是子線程要操作,就使用代理委托操作(這里不理解就在賦值方法那里打個斷點調試),FZ是具體操作的邏輯。就是這么簡單
這兩種方法我比較贊同第二種,雖然比第一種方法的代碼多,但是相對來說安全性也是有的。