gpt4 book ai didi

wpf - 约什·史密斯 (Josh Smith) 的 RelayCommand 实现是否存在缺陷?

转载 作者:行者123 更新时间:2023-12-03 07:10:31 24 4
gpt4 key购买 nike

考虑引用Josh Smith' article WPF Apps With The Model-View-ViewModel Design Pattern ,特别是 RelayCommand 的示例实现(如图 3 所示)。 (这个问题不需要通读整篇文章。)

总的来说,我认为实现非常出色,但我对 CanExecuteChanged 订阅委托(delegate)给 CommandManagerRequerySuggested 有疑问> 事件。 documentation for RequerySuggested状态:

Since this event is static, it will only hold onto the handler as a weak reference. Objects that listen for this event should keep a strong reference to their event handler to avoid it being garbage collected. This can be accomplished by having a private field and assigning the handler as the value before or after attaching to this event.

然而,RelayCommand 的示例实现并未为订阅的处理程序维护任何此类内容:

public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
  1. 这是否会将弱引用泄漏到 RelayCommand 的客户端,从而要求 RelayCommand 的用户了解 CanExecuteChanged 的实现并自己维护实时引用?
  2. 如果是这样,是否有意义,例如,将 RelayCommand 的实现修改为如下所示,以减轻 CanExecuteChanged 潜在的过早 GC > 订阅者:

    // This event never actually fires.  It's purely lifetime mgm't.
    private event EventHandler canExecChangedRef;
    public event EventHandler CanExecuteChanged
    {
    add
    {
    CommandManager.RequerySuggested += value;
    this.canExecChangedRef += value;
    }
    remove
    {
    this.canExecChangedRef -= value;
    CommandManager.RequerySuggested -= value;
    }
    }

最佳答案

我在 Josh 的 comment 中找到了答案关于他的“Understanding Routed Commands”文章:

[...] you have to use the WeakEvent pattern in your CanExecuteChanged event. This is because visual elements will hook that event, and since the command object might never be garbage collected until the app shuts down, there is a very real potential for a memory leak. [...]

争论似乎是,CanExecuteChanged 实现者只能弱地保留已注册的处理程序,因为 WPF Visuals 愚蠢到无法自行解开。通过委托(delegate)给 CommandManager 可以最轻松地实现这一点,而 CommandManager 已经执行了此操作。大概出于同样的原因。

关于wpf - 约什·史密斯 (Josh Smith) 的 RelayCommand 实现是否存在缺陷?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2281566/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com