winform 實現多線程更新UI控件的方法


 1  2 Control.CheckForIllegalCrossThreadCalls = false;//關閉安全檢查,為了安全一般不采用此代碼
 3 =============================================================================================================================
 4 
 5  6 一般多線程代碼:不能實現跨線程數據交互:
 7 Thread thread = new Thread(new ThreadStart(Test));
 8 thread.IsBackground = true;            
 9 thread.Start();
10 
11 ===============================================================================================================================
12 13 通過UI控件的Invoke/BeginInvoke方法更新,實現后台線程和UI線程數據交換
14 
15 1.定義一個委托
16 delegate void delegate1(string text);     //設置這個委托支持異步調用文本框控件的文本屬性。不同控件可能需要不同參數
17 
18 2.定義控件更新方法SetText                  //這個是實現線程數據交換的關鍵
19 private void SetText(string text)                                                         
20         {
21 
22             if (this.textBox1.InvokeRequired)            //如果調用控件的線程和創建創建控件的線程不是同一個則為True
23             {
24                 while (!this.textBox1.IsHandleCreated)
25                 {
26                     //解決窗體關閉時出現“訪問已釋放句柄“的異常
27                     if (this.textBox1.Disposing || this.textBox1.IsDisposed)
28                         return;
29                 }
30                 delegate1 d = new delegate1(SetText);  //委托實例化
31                 this.textBox1.Invoke(d, new object[] { text });
32             }
33             else
34             {
35                 this.textBox1.Text = text;
36             }
37         }
38 
39 3.次線程運行的主要代碼
40 private void test()
41         {
42             int i;
43             for (i = 1; i <= 10; i++)
44             {
45                 Thread.Sleep(1000);
46                 this.SetText(i.ToString());          //此處需要和UI線程實時交換數據,我們引用上門定義的方法SetText來實現,這一步是關鍵   
47             }
48             MessageBox.Show("運行完畢");
49 
50         }
51 4.控件事件代碼
52 private void button1_Click(object sender, EventArgs e)
53         {
54             Thread thread = new Thread(new ThreadStart(test));  //創建新線程
55             thread.IsBackground = true;                         //設定線程為后台線程
56             thread.Start();                                     //啟動新線程
57 
58         }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM