1.Control.Invoke
Invoke 委托会导致线程的阻塞,但是是顺序执行的,
private void Form1_Load(object sender, EventArgs e) { listBox1.Items.Add("begin"); listBox1.Invoke(new Action(() => { listBox1.Items.Add("invoke"); })); listBox1.Items.Add("after"); }
2.Control.BeginInvoke
BeginInvoke 委托同样会导致线程的阻塞,在执行完当前线程后才会执行,
private void Form1_Load(object sender, EventArgs e) { listBox1.Items.Add("begin"); listBox1.BeginInvoke(new Action(() => { listBox1.Items.Add("begininvoke"); })); listBox1.Items.Add("after"); }
若想要在线程执行结束之前执行 BeginInvoke,可以使用 EndInvoke,
private void Form1_Load(object sender, EventArgs e) { listBox1.Items.Add("begin"); var i = listBox1.BeginInvoke(new Action(() => { listBox1.Items.Add("begininvoke"); })); listBox1.EndInvoke(i); listBox1.Items.Add("after"); }
或者 BeginInvoke 会在一个 Invoke 调用前执行,
private void Form1_Load(object sender, EventArgs e) { listBox1.Items.Add("begin"); listBox1.BeginInvoke(new Action(() => { listBox1.Items.Add("begininvoke"); })); listBox1.Invoke(new Action(() => { listBox1.Items.Add("invoke"); })); listBox1.Items.Add("after"); }