使用匿名方法,省去了定义方法的步骤。实际上,在多线程编程的时候,使用匿名方法可以使得代码变的简化,并提高了可读性。下面代码是在不使用匿名方法的情况下编写多线程代码:
public void Run()
{
for (int i = 0; i < 1000000; i++)
{
this.textBox1.Text = i.ToString();
}
thread.Abort();
}
Thread thread = null;
private void button1_Click(object sender, EventArgs e)
{
CheckForIllegalCrossThreadCalls = false;
this.thread = new Thread(new ThreadStart (this.Run ));
this.thread.Start();
}
利用匿名方法,可以将上面的代码改写为:
private void button1_Click(object sender, EventArgs e)
{
CheckForIllegalCrossThreadCalls = false;
Thread thread = null;
thread = new Thread(
delegate()
{
for (int i = 0; i < 1000000; i++)
{
this.textBox1.Text = i.ToString();
}
thread.Abort();
}
);
thread.Start();
}
使用内联方式可以让代码更好理解!