Cannot convert anonymous method to type 'System.Delegate' because it is not a delegate type

c#, wpf

Solution

Anonymous functions (lambda expressions and anonymous methods) have to be converted to a specific delegate type, whereas `Dispatcher.BeginInvoke` just takes `Delegate`. There are two options for this...

Still use the existing `BeginInvoke` call, but specify the delegate type. There are various approaches here, but I generally extract the anonymous function to a previous statement:

Action action = delegate() { 
     this.Log.Add(...);
};
Dispatcher.BeginInvoke(action);

Write an extension method on `Dispatcher` which takes `Action` instead of `Delegate`:

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

Then you can call the extension method with the implicit conversion

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

I'd also encourage you to use lambda expressions instead of anonymous methods, in general:

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

EDIT: As noted in comments, `Dispatcher.BeginInvoke` gained an overload in .NET 4.5 which takes an `Action` directly, so you don't need the extension method in that case.

Problem

I want to execute this code on the main thread in the WPF app and getting an error I can't figure out what is wrong: ``` private void AddLog(string logItem) { this.Dispatcher.BeginInvoke( delegate() { this.Log.Add(new KeyValuePair<string, string>(DateTime.Now.ToLongTimeString(), logItem)); }); } ```

Original source

Related problems