Wednesday, May 4, 2011

Invoking anonymous methods in WPF

To execute some work on a Dispathcer, synchronously, the Dispatcher.Invoke method is used, which takes a Delegate as an argument representing the work to be done.

However, as stated on MSDN, the Delegate class is the base class for delegate types. However, only the system and compilers can derive explicitly from the Delegate class or from the MulticastDelegate class. It is also not permissible to derive a new type from a delegate type. The Delegate class is not considered a delegate type; it is a class used to derive delegate types. - Hence the need for the explicit cast to a derived-from-Delegate type.

Most languages implement a delegate keyword, and compilers for those languages are able to derive from the MulticastDelegate class; therefore, users should use the delegate keyword provided by the language.

Here are a few ways to synchronously invoke an anonymous method:

by declaring a delegate type and casting the delegate to it:

Starting with version 3.5, .Net contains an Action class that is defined like:

so it can be used:

by casting a delegate to an Action:

by casting a lambda expression to an Action:

by creating an instance of Action passing a delegate to its constructor: