It is not possible to convert an anonymous method to enter "System.Delegate" because it is not a delegate type

I want to execute this code in the main thread in a WPF application and get an error. I can not understand what is wrong:

private void AddLog(string logItem) { this.Dispatcher.BeginInvoke( delegate() { this.Log.Add(new KeyValuePair<string, string>(DateTime.Now.ToLongTimeString(), logItem)); }); } 
+8
c # wpf
source share
2 answers

Anonymous functions (lambda expressions and anonymous methods) must be converted to a specific type of delegate, while Dispatcher.BeginInvoke just accepts a Delegate . There are two options for this ...

  • Continue to use the existing BeginInvoke call, but specify the delegate type. There are various approaches here, but I usually extract the anonymous function in the previous statement:

     Action action = delegate() { this.Log.Add(...); }; Dispatcher.BeginInvoke(action); 
  • Write an extension method on Dispatcher that accepts Action instead of Delegate :

     public static void BeginInvokeAction(this Dispatcher dispatcher, Action action) { Dispatcher.BeginInvoke(action); } 

    Then you can call the extension method with implicit conversion

     this.Dispatcher.BeginInvokeAction( delegate() { this.Log.Add(...); }); 

I would also recommend using lambda expressions instead of anonymous methods:

 Dispatcher.BeginInvokeAction(() => this.Log.Add(...)); 

EDIT: As noted in the comments, Dispatcher.BeginInvoke got overloaded in .NET 4.5, which takes Action directly, so you don't need an extension method in this case.

+20
source share

You can also use MethodInvoker for this:

 private void AddLog(string logItem) { this.Dispatcher.BeginInvoke((MethodInvoker) delegate { this.Log.Add(new KeyValuePair<string, string>(DateTime.Now.ToLongTimeString(), logItem)); }); } 
+2
source share

All Articles