c# - WeakReference understanding -
i want create dictionary of viewmodels.
public static dictionary<string, weakreference> vmcollection = new dictionary<string, weakreference>();
adding this
vmcollection.add(name, new weakreference(viewmodel));
and calling required method this..
((vmcollection[viewmodel].target) baseviewmodel).newmessage(message);
do need maintain weakreference
? consequences if don't maintain weakreference
.
the consequence of not using weakreference
reference in dictionary prevent view model instances being garbage collected. weakreference
allows garbage collection (assuming there no other solid references elsewhere).
an item becomes eligible garbage collection when has no references it. weakreference
not create "countable" reference, can keep sort-of-reference it, still let eligible if weakreference
thing left looking @ it.
whether need or not depends on sort of life-cycle view models have. if need disposing or otherwise "letting go of", may need use weakreference
or expose way remove reference dictionary instead.
as mention in comments. tend err away using weakreference
opposed handling life-cycle of relevant objects explicitly. said, useful when don't have visibility of life-cycle @ relevant points. think in situation, should have necessary visibility, these in ui layer, , should try not use them.
here resources on topic:
guidelines extract above msdn link:
use long weak references when necessary state of object unpredictable after finalization.
avoid using weak references small objects because pointer may large or larger.
avoid using weak references automatic solution memory management problems. instead, develop effective caching policy handling application's objects.
i believe last guideline point applies situation.
Comments
Post a Comment