为什么在RelayCommand中引用较弱? [英] Why WeakReferences in RelayCommand?

查看:74
本文介绍了为什么在RelayCommand中引用较弱?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近从MVVMLight 3升级到了4,并注意到我的命令中断了.事实证明,在新的RelayCommand(在3.5版中实现)中使用弱引用会导致我正在使用的代码构造失败.我知道对于内存泄漏相关的弱引用有一些争论,我只是不理解.

I recently upgraded from MVVMLight 3 to 4, and noticed that my Commands broke. It turns out that the use of weak references in the new RelayCommand (implemented in version 3.5) were causing a code construct that I am using to fail. I know that there is some argument for weak refs relating to memory leak, I just don't understand it.

此操作失败:

private void InitCommand()
{
    Command = new SwitchMainGridCommand<SwitchMainGridToolViewModel>(this).Command;
}

通过失败,我的意思是,当我使用初始化并绑定到的Command属性时,其后备方法已被垃圾回收,并且Command无法执行.有趣的是,Command对象仍然存在,只是SwitchMainGridCommand上的支持属性现在消失了.在RelayCommand中的弱引用之前,即使未明确保留SwitchMainGridCommand,对Command的引用也使支持属性保持可用.

By fails, I mean that when I go to use the Command property that I had initialized and bound to, its backing methods have been garbage collected and the Command fails to execute. Interestingly, the Command object is still present, just the support properties on SwitchMainGridCommand are now gone. Before weak refs in RelayCommand, the ref to Command kept the support properties available as well, even though SwitchMainGridCommand was not being explicitly preserved.

成功:

SwitchMainGridCommand<SwitchMainGridToolViewModel> _refHolder = null;

private void InitCommand()
{
    _refHolder = new SwitchMainGridCommand<SwitchMainGridToolViewModel>(this);
    Command = _refHolder.Command;
}

在分配了Command的ViewModel上创建_refHolder类变量,这样可以避免收集_refHolder.Command引用的方法/属性.

Creating a _refHolder class variable on the ViewModel where Command is being assigned would keep the methods / properties that _refHolder.Command referenced from being collected.

我想这是弱引用的理想行为,但我不确定为什么会这样.

I guess this is the desired behavior of a weak reference, I am just not sure why it is desired.

推荐答案

以下是MSDN上有关弱引用和强引用的文章: MSDN优点

Here's an article from MSDN about weak vs. strong references: MSDN Goodness

这篇关于为什么在RelayCommand中引用较弱?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆