Lambda vs. (Action)delegate in Dispatcher.BeginInvoke

1.1k Views Asked by At

What is the difference between calling a Lambda function and explicitly invoking a delegate in Dispatcher? In other words, what is the difference between the following:

Dispatcher.BeginInvoke(new Action( () => Foo() ));

Dispatcher.BeginInvoke((Action)delegate () { Foo(); });

private void Foo() { }
2

There are 2 best solutions below

0
On BEST ANSWER

There is no difference. Both lines of code produce the same MSIL code (shown for example by ILSpy):

IL_000f: ldarg.0
IL_0010: call instance class [WindowsBase]System.Windows.Threading.Dispatcher [WindowsBase]System.Windows.Threading.DispatcherObject::get_Dispatcher()
IL_0015: ldarg.0
IL_0016: ldftn instance void WpfApplication2.MainWindow::'<.ctor>b__0_0'()
IL_001c: newobj instance void [mscorlib]System.Action::.ctor(object, native int)
IL_0021: ldc.i4.0
IL_0022: newarr [mscorlib]System.Object
IL_0027: callvirt instance class [WindowsBase]System.Windows.Threading.DispatcherOperation [WindowsBase]System.Windows.Threading.Dispatcher::BeginInvoke(class [mscorlib]System.Delegate, object[])
0
On

no difference.

in both case you define a anonymous method to call foo();

note : can be done like this

Dispatcher.BeginInvoke(Foo);