最近我在做一個項目,遇到了跨線程要去訪問頁面控件.但是總是提示出錯,不能在其它線程中修改創(chuàng)建控件的線程的控件的值,后來采用了匿名代理,結果很輕松地解決了.解決過程如下:
首先在窗體上,創(chuàng)建一個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>
/// 定義一個代理
/// </summary>
private delegate void CrossThreadOperationControl();
private void BackgroundProcess()
{
// 將代理實例化為一個匿名代理
CrossThreadOperationControl CrossDelete = delegate()
{
int i = 1;
while (i<5)
{
// 向列表框增加一個項目
listBox1.Items.Add("Item " + i.ToString());
i++;
}
label1.Text = "我在新線程里訪問這個lable!";
listBox1.Items.Add(label1.Text);
} ;
listBox1.Invoke(CrossDelete);
}
}
希望這個小技巧能夠?qū)δ愕牡膶W習和工作有所幫助.若有更好的辦法來解決跨線程訪問控件的問題,不防也拿出來大家分享一下.