C#中跨线程访问控件: 委托, Invoke, BeginInvoke

时间:2022-08-27 16:15:50
publicpartial 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);