Dispatcher。 BeginInvoke: 无法将 lambda 转换为 System

我试图调用 System.Windows.Threading.Dispatcher.BeginInvoke。该方法的签名如下:

BeginInvoke(Delegate method, params object[] args)

我正在尝试传递一个 Lambda 而不是创建一个代表。

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

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

不能将 lambda 转换为系统。

委托的签名以对象作为参数并返回 void。我的 lambda 和这个吻合,但是不管用。我错过了什么?

49157 次浏览

Since the method takes a System.Delegate, you need to give it a specific type of delegate, declared as such. This can be done via a cast or a creation of the specified delegate via new DelegateType as follows:

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

Also, as SLaks points out, Dispatcher.BeginInvoke takes a params array, so you can just write:

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

Or, if DoSomething is a method on this object itself:

_dispatcher.BeginInvoke(new Action(this.DoSomething));

Shorter:

_dispatcher.BeginInvoke((Action)(() => DoSomething()));

If you reference System.Windows.Presentation.dll from your project and add using System.Windows.Threading then you can access an extension method that allows you to use the lambda syntax.

using System.Windows.Threading;


...


Dispatcher.BeginInvoke(() =>
{
});

Using Inline Lambda...

Dispatcher.BeginInvoke((Action)(()=>{
//Write Code Here
}));

We create extension methods for this. E.g.

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

Now we can call it from within a form: this.BeginInvoke(() => { ... }).