因为
Invoke/
BeginInvoke接受
Delegate(而不是类型的委托),所以您需要告诉编译器要创建什么类型的委托;
MethodInvoker(2.0)或
Action(3.5)是常见选择(请注意,它们具有相同的签名);像这样:
control.Invoke((MethodInvoker) delegate {this.Text = "Hi";});如果需要传递参数,则可以使用“捕获的变量”:
string message = "Hi";control.Invoke((MethodInvoker) delegate {this.Text = message;});(注意:如果使用captures async ,则需要谨慎一点,但是 sync 很好-即上述情况很好)
另一种选择是编写扩展方法:
public static void Invoke(this Control control, Action action){ control.Invoke((Delegate)action);}然后:
this.Invoke(delegate { this.Text = "hi"; });// or since we are using C# 3.0this.Invoke(() => { this.Text = "hi"; });当然,您可以使用
BeginInvoke:
public static void BeginInvoke(this Control control, Action action){ control.BeginInvoke((Delegate)action);}如果不能使用C#3.0,则可以使用常规实例方法(大概是在
Form基类中)执行相同的操作。



