4

I am working on a WPF application in VS2008 and decided to reuse some code from another WPF application. However I have a strange issue with the following line:

Message.Dispatcher.Invoke(() => { Message.Text = "Looking for orders..."; });

This code works fine in the original application but throws the normal "Cannot convert lambda expression to type 'System.Delegate' because it is not a delegate type" error in the new application.

I know I can cast the expression as an Action to get it to work; but I am curious as to why the same piece of code compiles and works in one project but not another.

oliver
  • 157
  • 2
  • 8

1 Answers1

6

There might be an extension method defined somewhere in the old project that handles the casting!

Something like:

public static void Invoke(this Dispatcher dispatcher, Action action)
{
    dispatcher.Invoke((Delegate)action);
}

Then you could just do the following without trouble:

Message.Dispatcher.Invoke(() => { Message.Text = "Looking for orders..."; });

Update:
Turns out the .NET Framework has a set of extension methods for Dispatcher that can handle these kind of things build in already.

http://msdn.microsoft.com/en-us/library/system.windows.threading.dispatcherextensions.aspx

Peter Hansen
  • 8,807
  • 1
  • 36
  • 44
  • Hi Peter. Thanks for the answer. I looked for extension methods within the code; but didn't find any. However I did find a DispatcherExtensions class that is linked in from the System.Windows.Threading namespace. – oliver Jul 14 '12 at 10:46
  • 7
    Just in case anyone else is interested; adding a reference to System.Windows.Presentation.dll include the DispatcherExtensions class – oliver Jul 14 '12 at 11:04
  • Hi Oliver. Cool - didn't know about this class. I have updated the answer with a link to the documentation of the class. – Peter Hansen Jul 14 '12 at 11:10