Why WeakReferences in RelayCommand?

2020-07-23 06:44发布

问题:

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.

This fails:

private void InitCommand()
{
    Command = new SwitchMainGridCommand<SwitchMainGridToolViewModel>(this).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.

This succeeds:

SwitchMainGridCommand<SwitchMainGridToolViewModel> _refHolder = null;

private void InitCommand()
{
    _refHolder = new SwitchMainGridCommand<SwitchMainGridToolViewModel>(this);
    Command = _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.

回答1:

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



回答2:

Maybe, and I repeat maybe for this reason:

In MvvmLight logic, and in other mvvm style, the ViewModel is "link" to the view using the Locator. Now when in your xaml page move forward to next page Vm of previous page still live, using command weak give able to easy release the memory.

The second is simple for better controlling life of object letting the locator the only which holding reference of the Viewmodel hence the only can decide where and when release

I hope this may help you, I thing imho if a vm still live for a while isn't really important, and mainly when your software not use really huge size of memory. Alloc and dealloc affect badly affected the performance of software