Dispatcher.BeginInvoke: Cannot convert lambda to System.Delegate

I am trying to call System.Windows.Threading.Dispatcher.BeginInvoke . The signature of the method is as follows:

 BeginInvoke(Delegate method, params object[] args) 

I am trying to pass Lambda to it instead of creating a delegate.

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

This gives me a compiler error saying that I cannot convert lambda to System.Delegate. The delegate signature accepts the object as a parameter and returns void. My lambda matches this, but it doesn't work. What am I missing?

+62
c # lambda begininvoke wpf dispatcher
Feb 08 2018-11-18T00:
source share
4 answers

Since the method accepts System.Delegate , you need to tell it a specific delegate type declared as such. This can be done by creating or creating the specified delegate through the new DelegateType as follows:

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

Also, since SLaks points out, Dispatcher.BeginInvoke accepts an array of params, so you can simply write:

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

Or, if DoSomething is the method for this object:

 _dispatcher.BeginInvoke(new Action(this.DoSomething)); 
+59
Feb 08 '11 at 17:50
source share

In short:

 _dispatcher.BeginInvoke((Action)(() => DoSomething())); 
+58
Oct 06 '11 at 1:50
source share

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

 using System.Windows.Threading; ... Dispatcher.BeginInvoke(() => { }); 
+5
Nov 24 '14 at 11:16
source share

Using Inline Lambda ...

 Dispatcher.BeginInvoke((Action)(()=>{ //Write Code Here })); 
+5
Jan 07 '16 at 16:10
source share



All Articles