如何在多線程中調用winform窗體控件

如何在多線程中調用winform窗體控件

下午在糾結之前來窗體的一個異步問題,在網上查到了一個自認爲很不錯的文章,這個轉載出來,希望和大家一起交流學習。

文章如下:

由於 Windows 窗體控件本質上不是線程安全的。因此如果有兩個或多個線程適度操作某一控件的狀態(set value),則可能會迫使該控件進入一種不一致的狀態。還可能出現其他與線程相關的 bug,包括爭用和死鎖的情況。於是在調試器中運行應用程序時,如果創建某控件的線程之外的其他線程試圖調用該控件,則調試器會引發一個 InvalidOperationException

本文用一個很簡單的示例來講解這個問題(在窗體上放一個TextBox和一個Button,點擊Button後,在新建的線程中設置TextBox的值)

解決辦法一: 關閉該異常檢測的方式來避免異常的出現

經過測試發現此種方法雖然避免了異常的拋出,但是並不能保證程序運行結果的正確性 (比如多個線程同時設置TextBox1的Text時,很難預計最終TextBox1的Text是什麼)

1using System;
2using System.Collections.Generic;
3using System.ComponentModel;
4using System.Data;
5using System.Drawing;
6using System.Text;
7using System.Windows.Forms;
8using System.Threading;
9
10namespace winformTest
11{
12    public partial class Form1 : Form
13    {
14        public Form1()
15        {
16            InitializeComponent();
17            Control.CheckForIllegalCrossThreadCalls = false;//這一行是關鍵      
18        }
19        
20
21        private void button1_Click(object sender, EventArgs e)
22        {
23            SetTextBoxValue();
24        }
25
26        void SetTextBoxValue()
27        {
28            TextBoxSetValue tbsv = new TextBoxSetValue(this.textBox1, "Method1");
29            ThreadStart TS = new ThreadStart(tbsv.SetText);
30            Thread T = new Thread(TS);
31            T.Start();
32        }
33
34
35        class TextBoxSetValue
36        {
37            private TextBox _TextBox ;
38            private string _Value;
39
40            public TextBoxSetValue(TextBox TxtBox, String Value) 
41            {
42                _TextBox = TxtBox;
43                _Value = Value;
44            }
45
46            public void SetText() 
47            {
48                _TextBox.Text = _Value;
49            }
50        }
51    }
52}
解決辦法二:通過委託安全調用
1using System;
2using System.Collections.Generic;
3using System.ComponentModel;
4using System.Data;
5using System.Drawing;
6using System.Text;
7using System.Windows.Forms;
8
9namespace winformTest
10{
11    public partial class Form2 : Form
12    {
13        public Form2()
14        {
15            InitializeComponent();
16        }
17 
18
19        private void button1_Click(object sender, EventArgs e)
20        {
21            SetTextBoxValue();
22        }        
23
24       
25        private delegate void CallSetTextValue();
26        //通過委託調用
27        void SetTextBoxValue() 
28        {
29            TextBoxSetValue tbsv = new TextBoxSetValue(this.textBox1, "Method2");
30            if (tbsv.TextBox.InvokeRequired)
31            {
32                CallSetTextValue call = new CallSetTextValue(tbsv.SetText);
33                tbsv.TextBox.Invoke(call);               
34            }
35            else
36            {
37                tbsv.SetText();
38            }
39        }
40
41
42        class TextBoxSetValue
43        {
44            private TextBox _TextBox;
45            private string _Value;
46
47            public TextBoxSetValue(TextBox TxtBox, String Value)
48            {
49                _TextBox = TxtBox;
50                _Value = Value;
51            }
52
53            public void SetText()
54            {
55                _TextBox.Text = _Value;
56            }
57
58
59            public TextBox TextBox {
60                set { _TextBox = value; }
61                get { return _TextBox; }
62            }           
63        }
64    }
65}

第三解決辦法:利用BackgroundWorker控件
1using System;
2using System.Collections.Generic;
3using System.ComponentModel;
4using System.Data;
5using System.Drawing;
6using System.Text;
7using System.Windows.Forms;
8using System.Threading;
9
10namespace winformTest
11{
12    public partial class Form3 : Form
13    {
14        public Form3()
15        {
16            InitializeComponent();
17        }
18
19        private void button1_Click(object sender, EventArgs e)
20        { 
21            using (BackgroundWorker bw = new BackgroundWorker())
22            {
23                bw.RunWorkerCompleted += SetTextBoxValue;
24                bw.RunWorkerAsync();
25            }
26        } 
27        
28        void SetTextBoxValue(object sender, RunWorkerCompletedEventArgs e) 
29        {
30            TextBoxSetValue tbsv = new TextBoxSetValue(this.textBox1, "Method3");
31            tbsv.SetText();
32        }
33
34
35        class TextBoxSetValue
36        {
37            private TextBox _TextBox;
38            private string _Value;
39
40            public TextBoxSetValue(TextBox TxtBox, String Value)
41            {
42                _TextBox = TxtBox;
43                _Value = Value;
44            }
45
46            public void SetText()
47            {
48                _TextBox.Text = _Value;
49            }
50        }
51
52    }
53}

 

用戶不喜歡反應慢的程序。在執行耗時較長的操作時,使用多線程是明智之舉,它可以提高程序 UI 的響應速度,使得一切運行顯得更爲快速。在 Windows 中進行多線程編程曾經是 C++ 開發人員的專屬特權,但是現在,可以使用所有兼容 Microsoft .NET 的語言來編寫。

不過Windows 窗體體系結構對線程使用制定了嚴格的規則。如果只是編寫單線程應用程序,則沒必要知道這些規則,這是因爲單線程的代碼不可能違反這些規則。然而,一旦採用多線程,就需要理解 Windows 窗體中最重要的一條線程規則:除了極少數的例外情況,否則都不要在它的創建線程以外的線程中使用控件的任何成員。本規則的例外情況有文檔說明,但這樣的情況非常少。這適用於其類派生自 System.Windows.Forms.Control 的任何對象,其中幾乎包括 UI 中的所有元素。所有的 UI 元素(包括表單本身)都是從 Control 類派生的對象。此外,這條規則的結果是一個被包含的控件(如,包含在一個表單中的按鈕)必須與包含它控件位處於同一個線程中。也就是說,一個窗口中的所有控件屬於同一個 UI 線程。實際中,大部分 Windows 窗體應用程序最終都只有一個線程,所有 UI 活動都發生在這個線程上。這個線程通常稱爲 UI 線程。這意味着您不能調用用戶界面中任意控件上的任何方法,除非在該方法的文檔說明中指出可以調用。該規則的例外情況(總有文檔記錄)非常少而且它們之間關係也不大。請注意,以下代碼是非法的:

        private Thread myThread;

        private void Form1_Load(object sender, EventArgs e)

        {

            myThread = new Thread(new ThreadStart(RunsOnWorkerThread));

            myThread.Start();

        }

        private void RunsOnWorkerThread()

        {

            label1.Text = "myThread線程調用UI控件";

    }

如果您在 .NET Framework 1.0 版本中嘗試運行這段代碼,也許會僥倖運行成功,或者初看起來是如此。這就是多線程錯誤中的主要問題,即它們並不會立即顯現出來。甚至當出現了一些錯誤時,在第一次演示程序之前一切看起來也都很正常。但不要搞錯 — 我剛纔顯示的這段代碼明顯違反了規則,並且可以預見,任何抱希望於“試運行時良好,應該就沒有問題”的人在即將到來的調試期是會付出沉重代價的。

 

下面我們來看看有哪些方法可以解決這一問題。

 

一、System.Windows.Forms.MethodInvoker 類型是一個系統定義的委託,用於調用不帶參數的方法。

        private Thread myThread;

        private void Form1_Load(object sender, EventArgs e)

        {

            myThread = new Thread(new ThreadStart(RunsOnWorkerThread));

            myThread.Start();

        }

        private void RunsOnWorkerThread()

        {

            MethodInvoker mi = new MethodInvoker(SetControlsProp);

            BeginInvoke(mi);

        }

        private void SetControlsProp()

        {

            label1.Text = "myThread線程調用UI控件";

        }
 


二、直接用System.EventHandle(可帶參數)

        private Thread myThread;

        private void Form1_Load(object sender, EventArgs e)

        {

            myThread = new Thread(new ThreadStart(RunsOnWorkerThread));

            myThread.Start();

        }

        private void RunsOnWorkerThread()

        {

            //DoSomethingSlow();

            string pList = "myThread線程調用UI控件";

            label1.BeginInvoke(new System.EventHandler(UpdateUI), pList);

        }

        //直接用System.EventHandler,沒有必要自定義委託

        private void UpdateUI(object o, System.EventArgs e)

        {

           //UI線程設置label1屬性

            label1.Text = o.ToString() + "成功!";

        }

 

三、包裝 Control.Invoke

 

雖然第二個方法中的代碼解決了這個問題,但它相當繁瑣。如果輔助線程希望在結束時提供更多的反饋信息,而不是簡單地給出“Finished!”消息,則 BeginInvoke過於複雜的使用方法會令人生畏。爲了傳達其他消息,例如“正在處理”、“一切順利”等等,需要設法向 UpdateUI 函數傳遞一個參數。可能還需要添加一個進度欄以提高反饋能力。這麼多次調用 BeginInvoke 可能導致輔助線程受該代碼支配。這樣不僅會造成不便,而且考慮到輔助線程與 UI 的協調性,這樣設計也不好。對這些進行分析之後,我們認爲包裝函數可以解決這兩個問題。

        private Thread myThread;

        private void Form1_Load(object sender, EventArgs e)

        {

            myThread = new Thread(new ThreadStart(RunsOnWorkerThread));

            myThread.Start();

        }

        private void RunsOnWorkerThread()

        {

            ////DoSomethingSlow();

            for (int i = 0; i < 100; i++)

            {

                ShowProgress( Convert.ToString(i)+"%", i);

                Thread.Sleep(100);

            }

        }

        public void ShowProgress(string msg, int percentDone)

        {

            // Wrap the parameters in some EventArgs-derived custom class:

            System.EventArgs e = new MyProgressEvents(msg, percentDone);

            object[] pList = { this, e };

 

            BeginInvoke(new MyProgressEventsHandler(UpdateUI), pList);

        }

        private delegate void MyProgressEventsHandler(object sender, MyProgressEvents e);

        private void UpdateUI(object sender, MyProgressEvents e)

        {

            lblStatus.Text = e.Msg;

            myProgressControl.Value = e.PercentDone;

       }

    public class MyProgressEvents : EventArgs

    {

        public string Msg;

        public int PercentDone;

        public MyProgressEvents(string msg, int per)

        {

            Msg = msg;

            PercentDone = per;

        }

}

ShowProgress 方法對將調用引向正確線程的工作進行封裝。這意味着輔助線程代碼不再擔心需要過多關注 UI 細節,而只要定期調用 ShowProgress 即可。

如果我提供一個設計爲可從任何線程調用的公共方法,則完全有可能某人會從 UI 線程調用這個方法。在這種情況下,沒必要調用 BeginInvoke,因爲我已經處於正確的線程中。調用 Invoke 完全是浪費時間和資源,不如直接調用適當的方法。爲了避免這種情況,Control 類將公開一個稱爲 InvokeRequired 的屬性。這是“只限 UI 線程”規則的另一個例外。它可從任何線程讀取,如果調用線程是 UI 線程,則返回假,其他線程則返回真。這意味着我可以按以下方式修改包裝:

        public void ShowProgress(string msg, int percentDone)

        {

            if (InvokeRequired)

            {

                // As before

                //...

            }

            else

            {

                // We're already on the UI thread just

                // call straight through.

                UpdateUI(this, new MyProgressEvents(msg,PercentDone));

            }

        }

線程打開窗體的問題:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace WindowsApplication36
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
            new System.Threading.Thread(new System.Threading.ThreadStart(invokeShow)).Start();
        }
        public void invokeShow()
        {
             Form f1 = new Form();
             this.Invoke(new System.EventHandler(this.showForm), new object[] { f1, null });
        }
        public void showForm(object sender,EventArgs e)
        {
            Form f1 = sender as Form;
            f1.ShowDialog();
        }
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章