这两者的区别在于委托的BeginInvoke方法是新起一个线程(辅助后台线程)来执行委托,而原线程继续往下执行;Control.BeginInvoke则是将委托强制传递至UI线程执行,所以可能会造成UI线程假死。
所以想要执行异步,应该用delegate的BeginInvoke方法;而Control.BeginInvoke方法主要用途是让子线程可以跨线程操作UI线程的控件。
Control.BeginInvoke(Delegate, Object[])方法使用实例:
注:另一种重构方法是Control.BeginInvoke(Delegate)
public delegate void MyDelegate(Label myControl, string myArg2); private void Button_Click(object sender, EventArgs e) { object[] myArray = new object[2]; myArray[0] = new Label(); myArray[1] = "Enter a Value"; myTextBox.BeginInvoke(new MyDelegate(DelegateMethod), myArray); } public void DelegateMethod(Label myControl, string myCaption) { myControl.Location = new Point(16,16); myControl.Size = new Size(80, 25); myControl.Text = myCaption; this.Controls.Add(myControl); }说明: Control.BeginInvoke (Delegate, Object[]) 方法中arg是传给Delegate委托中方法的,且参数签名一致。如上例中
myArray[0],myArray[1]分别传递给MyDelegate委托中DelegateMethod方法。