private void button1_Click(object sender, EventArgs e) { this.textBox1.Text = "1"; this.Invoke(new EventHandler(delegate { this.textBox1.Text += "2"; })); this.textBox1.Text += "3"; }
結果為:123
private void button1_Click(object sender, EventArgs e) { this.textBox1.Text = "1"; this.BeginInvoke(new EventHandler(delegate { this.textBox1.Text += "2"; })); this.textBox1.Text += "3"; }
結果為132
結論:1、Invoke會阻止當前主線程的運行;BeginInvoke不會阻止當前主線程的運行,而是等當前主線程做完事情之后再執行BeginInvoke中的代碼內容。
2、這2個方法都是由主線程運行的,並不是異步執行,如果代碼耗時過長,同樣會造成界面卡死
Invoke阻止的是工作線程,相當於阻塞式(非創建控件線程或主線程),BeginInvoke是不等待主線程完成變立刻返回執行下面操作,相當於異步式。
這里的阻塞或異步是相對於工作線程,而非主線程。
它阻塞或異步的是調用Invoke或BeginInvoke的線程。
