C# 2.0 匿名方法大大简化了 Windows Forms 异步调用的实现,我们再也不用手工定义异步委托或者包装类了。例如,在下面的代码示例中,Form1 有一个按钮控件和一个列表控件,在按钮控件的单击事件里,我们新建一个线程,在这个线程中向列表控件添加 10 个项目:
public class Form1 : System.Windows.Forms.Form
{
private System.Windows.Forms.ListBox listBox1;
private System.Windows.Forms.Button button1;
...
private void button1_Click(object sender, EventArgs e)
{
Thread thread = new Thread(this.ThreadProc);
thread.Start();
}
private void ThreadProc()
{
for (int i = 0; i < 10; i++)
{
this.Invoke((MethodInvoker)delegate
{
this.listBox1.Items.Add("Item " + (i + 1).ToString());
});
}
}
}
本文地址:http://com.8s8s.com/it/it43786.htm