Dispatcher.BeginInvoke: Cannot convert lambda to System.Delegate

C#WpfLambdaDispatcherBegininvoke

C# Problem Overview


I'm trying to call System.Windows.Threading.Dispatcher.BeginInvoke. The signature of the method is this:

BeginInvoke(Delegate method, params object[] args)

I'm trying to pass it a Lambda instead of having to create a Delegate.

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

It's giving me a compiler error saying that I

> can't convert the lambda to a System.Delegate.

The signature of the delegate takes an object as a parameter and returns void. My lambda matches this, yet it's not working. What am I missing?

C# Solutions


Solution 1 - C#

Shorter:

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

Solution 2 - C#

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));

Solution 3 - C#

Using Inline Lambda...

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

Solution 4 - C#

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(() =>
{
});

Solution 5 - C#

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(() => { ... }).

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMicahView Question on Stackoverflow
Solution 1 - C#Erwin MayerView Answer on Stackoverflow
Solution 2 - C#Reed CopseyView Answer on Stackoverflow
Solution 3 - C#JWPView Answer on Stackoverflow
Solution 4 - C#logicnet.dkView Answer on Stackoverflow
Solution 5 - C#Shaun LuttinView Answer on Stackoverflow