C#中跨线程访问控件: 委托, Invoke, BeginInvoke
多线程应用中经常要跨线程访问窗体控件, 但在 C#中是不允许直接从非拥有控件的线程中访问控件的, 必须通过委托的方式安全调用, 如下示例所示:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Thread newThread = new Thread(new ThreadStart(SetLabel));
newThread.Start();
}
private void SetLabel()
{
CrossDelegate dl = new CrossDelegate(Done);
string text = "test";
this.BeginInvoke(dl, "delegate three"); // 异步调用委托,调用后立即返回并立即执行下面的语句
//this.Invoke(dl, text); // 等待工作线程完成后, 才接着执行下面的语句.
MessageBox.Show("委托调用返回了", "观察委托调用的反应效果");
}
private void Done(string text)
{
label1.Text = text;
Thread.Sleep(2000);
}
}
public delegate void CrossDelegate(string text);
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Thread newThread = new Thread(new ThreadStart(SetLabel));
newThread.Start();
}
private void SetLabel()
{
CrossDelegate dl = new CrossDelegate(Done);
string text = "test";
this.BeginInvoke(dl, "delegate three"); // 异步调用委托,调用后立即返回并立即执行下面的语句
//this.Invoke(dl, text); // 等待工作线程完成后, 才接着执行下面的语句.
MessageBox.Show("委托调用返回了", "观察委托调用的反应效果");
}
private void Done(string text)
{
label1.Text = text;
Thread.Sleep(2000);
}
}
public delegate void CrossDelegate(string text);
~做事情贵在坚持~