在開(kāi)發(fā)具有線程的應(yīng)用程序時(shí),有時(shí)會(huì)通過(guò)子線程實(shí)現(xiàn)Windows窗體,,以及控件的操作,,比如:在對(duì)文件進(jìn)行復(fù)制時(shí),為了使用戶(hù)可以更好的觀察到文件的復(fù)制情況,,可以在指定的Windows窗體上顯示一個(gè)進(jìn)度條,,為了避免文件復(fù)制與進(jìn)度條的同時(shí)操作所帶來(lái)的機(jī)器假死狀態(tài),,可以用子線程來(lái)完成文件復(fù)制與進(jìn)度條跟蹤操作,下面以簡(jiǎn)單的例子在子線程中操作窗體中的TextBox控件,。代碼如下: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Threading;//添加線程的命名空間 namespace ppp { public partial class Form1 : Form { public Form1() { InitializeComponent(); } Thread t; //定義線程變量 private void button1_Click(object sender, EventArgs e) { t = new Thread(new ThreadStart(Threadp)); //實(shí)例化線程 t.Start();//啟動(dòng)線程 } 自定義方法Threadp,,主要用于線程的調(diào)用。代碼如下: public void Threadp() { textBox1.Text = '實(shí)現(xiàn)在子線程中操作主線程中的控件'; t.Abort();//關(guān)閉線程 } } 圖1 在子線程中操作主線程中控件的錯(cuò)誤提示信息: 以上是通過(guò)一個(gè)子線程來(lái)操作主線程中的控件,,但是,,這樣作會(huì)出現(xiàn)一個(gè)問(wèn)題(如圖1所示),,就是TextBox控件是在主線程中創(chuàng)建的,,在子線程中并沒(méi)有對(duì)其進(jìn)行創(chuàng)建,也就是從不是創(chuàng)建控件的線程訪問(wèn)它,。那么,,如何解決跨線程調(diào)用Windows窗體控件呢?可以用線程委托實(shí)現(xiàn)跨線程調(diào)用Windows窗體控件,。下面將上一個(gè)例子進(jìn)行一下改動(dòng),。代碼如下: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Threading;//添加線程的命名空間 namespace ppp { public partial class Form1 : Form { public Form1() { InitializeComponent(); } Thread t; //定義線程變量 private void button1_Click(object sender, EventArgs e) { t = new Thread(new ThreadStart(Threadp)); //實(shí)例化線程 t.Start();//啟動(dòng)線程 } private delegate void setText();//定義一個(gè)線程委托 自定義方法Threadp,主要用于線程的調(diào)用,。代碼如下: public void Threadp() { setText d = new setText(Threading); //實(shí)例化一個(gè)委托 this.Invoke(d); //在擁用此控件的基礎(chǔ)窗體句柄的線程上執(zhí)行指定的委托 } 自定義方法Threading,,主要作于委托的調(diào)用。代碼如下: public void Threading() { textBox1.Text = '實(shí)現(xiàn)在子線程中操作主線程中的控件'; t.Abort();//關(guān)閉線程 } } } |
|
來(lái)自: VeryHappyAG > 《編程》