84

我试着打电话System.Windows.Threading.Dispatcher.BeginInvoke。该方法的签名是这样的:

BeginInvoke(Delegate method, params object[] args)

我正在尝试将 Lambda 传递给它,而不必创建一个委托。

_dispatcher.BeginInvoke((sender) => { DoSomething(); }, new object[] { this } );

它给了我一个编译器错误,说我

无法将 lambda 转换为 System.Delegate。

委托的签名将对象作为参数并返回 void。我的 lambda 与此匹配,但它不起作用。我错过了什么?

4

5 回答 5

76

更短:

_dispatcher.BeginInvoke((Action)(() => DoSomething()));
于 2011-10-06T01:50:50.637 回答
72

由于该方法采用System.Delegate,因此您需要为其提供特定类型的委托,并声明为这样。这可以通过强制转换或通过 new DelegateType 创建指定的委托来完成,如下所示:

_dispatcher.BeginInvoke(
     new Action<MyClass>((sender) => { DoSomething(); }),
     new object[] { this } 
  );

此外,正如SLaks指出的那样,Dispatcher.BeginInvoke需要一个 params 数组,所以你可以写:

_dispatcher.BeginInvoke(
     new Action<MyClass>((sender) => { DoSomething(); }),
     this
  );

或者,如果 DoSomething 是此对象本身的方法:

_dispatcher.BeginInvoke(new Action(this.DoSomething));
于 2011-02-08T17:50:13.750 回答
10

使用内联 Lambda...

Dispatcher.BeginInvoke((Action)(()=>{
  //Write Code Here
}));
于 2016-01-07T16:10:45.273 回答
7

如果您从项目中引用 System.Windows.Presentation.dll 并添加,using System.Windows.Threading那么您可以访问允许您使用 lambda 语法的扩展方法。

using System.Windows.Threading;

...

Dispatcher.BeginInvoke(() =>
{
});
于 2014-11-24T11:16:16.370 回答
3

我们为此创建扩展方法。例如

public static void BeginInvoke(this Control control, Action action)
    => control.BeginInvoke(action);

现在我们可以在表单中调用它:this.BeginInvoke(() => { ... }).

于 2018-05-17T17:14:11.557 回答