I want to create the dictionary of all the ViewModels.
public static Dictionary<string, WeakReference> vmCollection = new Dictionary<string, WeakReference>();
Adding it like this
vmCollection.Add(name, new WeakReference(viewModel));
And calling the required method like this..
((vmCollection[viewModel].Target) as BaseViewModel).NewMessage(message);
Do I need maintain it as a WeakReference
? What could be the consequences if I don't maintain it as a WeakReference
.
Best Answer
The only consequence of not using a
WeakReference
is that the reference in your dictionary will prevent the View Model instances from being garbage collected. AWeakReference
allows garbage collection (assuming there are no other solid references elsewhere).An item becomes eligible for garbage collection when it has no references to it.
WeakReference
does not create a "countable" reference, thus you can keep a sort-of-reference to it, but still let it be eligible if yourWeakReference
is the only thing left looking at it.Whether you need it or not really depends on what sort of life-cycle your View Models have. If they need disposing or otherwise "letting go of", then you may need to use
WeakReference
or expose a way to remove the reference from the dictionary instead.As I mention in the comments. I tend to err away from using
WeakReference
as opposed to handling the life-cycle of the relevant objects explicitly. That said, they are useful when you simply don't have visibility of the life-cycle at the relevant points. I think in your situation, you should have the necessary visibility, as these are all likely in the UI layer, and thus should try to not use them.Here is a resource on the topic:
Guidelines extract from the above MSDN link:
I believe the last guideline point applies to your situation.