最近我在做一個(gè)項(xiàng)目,遇到了跨線程要去訪問頁(yè)面控件.但是總是提示出錯(cuò),不能在其它線程中修改創(chuàng)建控件的線程的控件的值,后來(lái)采用了匿名代理,結(jié)果很輕松地解決了.解決過程如下: 首先在窗體上,創(chuàng)建一個(gè)listbox,lable. using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Threading;
namespace AccessControl { public partial class Form1 : Form { public Form1() { InitializeComponent(); }
private void Form1_Load(object sender, EventArgs e) { Thread newthread = new Thread(new ThreadStart(BackgroundProcess)); newthread.Start();
}
/// <summary> /// 定義一個(gè)代理 /// </summary> private delegate void CrossThreadOperationControl();
private void BackgroundProcess() { // 將代理實(shí)例化為一個(gè)匿名代理 CrossThreadOperationControl CrossDelete = delegate() { int i = 1; while (i<5) { // 向列表框增加一個(gè)項(xiàng)目 listBox1.Items.Add("Item " + i.ToString()); i++; } label1.Text = "我在新線程里訪問這個(gè)lable!"; listBox1.Items.Add(label1.Text); } ; listBox1.Invoke(CrossDelete); }
} } 希望這個(gè)小技巧能夠?qū)δ愕牡膶W(xué)習(xí)和工作有所幫助.若有更好的辦法來(lái)解決跨線程訪問控件的問題,不防也拿出來(lái)大家分享一下.
|