Dispatcher.BeginInvoke 中的 Lambda 与(动作)委托

Lambda vs. (Action)delegate in Dispatcher.BeginInvoke

在 Dispatcher 中调用 Lambda 函数和显式调用委托有什么区别?换句话说,以下有什么区别:

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

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

private void Foo() { }

没有区别。

在这两种情况下,您都定义了一个匿名方法来调用 foo();

注意:可以这样做

Dispatcher.BeginInvoke(Foo);

没有区别。两行代码产生相同的 MSIL code(例如 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[])