【问题标题】:Dispatcher.Invoke and lambda syntax - new ActionDispatcher.Invoke 和 lambda 语法 - 新操作
【发布时间】:2017-09-15 08:38:17
【问题描述】:

有什么区别

Application.Current.Dispatcher.Invoke(
    new Action(() =>
    {
        txtRowCount.Text = string.Format("{0}", rowCount);
    })
); //end-Invoke

Application.Current.Dispatcher.Invoke(
    () =>
    {
        txtRowCount.Text = string.Format("{0}", rowCount);
    }
); //end-Invoke

如果编译器抱怨,我会使用另一个,但我不知道到底发生了什么。

【问题讨论】:

  • 它们是一样的。第二个 sn-p 中的 lambda 被隐式转换为一个动作。虽然通常相同,但我也建议使用 TextBlock 的调度程序,例如 txtRowCount.Dispatcher.Invoke(() => txtRowCount.Text = string.Format("{0}", rowCount));

标签: wpf lambda delegates


【解决方案1】:

这很可能取决于您调用哪个方法并将委托传递给。例如,具有这样签名的方法可以使用 lambda 隐式创建 Action

void RunAction(Action thing) {}

而像这样的方法无法确定您想要什么类型的委托:

void RunDelegate(Delegate thing) {}

这样做的原因是Delegate 类型是可以表示任何delegate 表达式的基类。例如,您可以将第二个函数传递给 ActionFunc<T>Predicate<T>EventHandler 或您能想到的任何其他委托,包括自定义委托。在这种情况下,编译器/运行时不知道将您的自定义委托转换为什么。函数有责任弄清楚如何调用委托,或者如果它不理解则抛出异常。

另一方面,Action 是没有参数且不返回值的方法的特定委托:

delegate void Action();

因此,当方法具有类型为 Action 的参数时,任何具有符合该委托的签名的 lambda 都可以为您隐式转换。


对于采用DelegateDispatcher.BeginInvoke 方法,您可以将任何接受0 参数的委托传递给它(如果它返回一些东西很好,但我怀疑返回值用于任何用途)。因此,您可以将其传递给ActionFunc<T>。如果您向它传递一个期望传递给它的参数的委托,它仍然会编译,但会在 Dispatcher 尝试调用该方法时在运行时抛出异常。

为了演示,我制作了一个快速的小控制台应用程序。

static int Main(string[] args)
{
    // These work
    Dispatcher.CurrentDispatcher.BeginInvoke(new Action(() => Console.WriteLine("Action")));
    Dispatcher.CurrentDispatcher.BeginInvoke(new Func<int>(() => { Console.WriteLine("Func<int>"); return 42; }));

    // This one throws a TargetParameterCountException when the dispatcher gets to it
    //Dispatcher.CurrentDispatcher.BeginInvoke(new Action<bool>(b => Console.WriteLine("Action<bool>")));

    // Queue a dispatcher shutdown at the end and run the dispatcher
    Dispatcher.CurrentDispatcher.BeginInvoke(new Action(() => Dispatcher.CurrentDispatcher.InvokeShutdown()));
    Dispatcher.Run();

    Console.WriteLine("Press any key to exit...");
    Console.ReadKey();
    return 0;
}

【讨论】:

    猜你喜欢
    • 2011-12-04
    • 1970-01-01
    • 1970-01-01
    • 2013-12-28
    • 2014-02-23
    • 1970-01-01
    • 2010-11-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多