Destroying a screen completely from memory

Feb 15, 2011 at 11:20 PM
Edited Feb 15, 2011 at 11:25 PM

I am sure someone must have encountered the same problem, but I was unable to find a solution online

My application
Parent Conductor > Login Screen, Other screens(conductors) etc > Sub screens

Based on the users actions we create the instances of screens used and close them using TryClose() when they close a subscreen or say logout.

But I see that when I create a new instance of any screen of type which was closed, and create a new one; the older screen which was closed using TryClose() is still in memory.
So if the older screens use EventAggregator and subscribe, they still listen and the respective methods get invoked when I want only one invokation which is in the new screens. I dont want service calls to be made multiple times due to the older screens acting in memory.

FYI, I am using Unity container to create instances.

Any help is greately appreciated as this is bloating our business application and slowing down by invoking unexpected service calls.

Feb 16, 2011 at 12:21 AM

I recommend that you override OnDeactivate in your screens and if the screen is closing, unsubscribe yourself from the EventAggregator. The EA uses WeakReferences as a preventative measure only. Realize that they may not get cleaned up until the garbage collector kicks in. So, it's always better to unsubscribe manually if you know the screen is being discarded.

Feb 16, 2011 at 1:19 AM

Thank you Eisenberg for a prompt suggestion.

That would work in case we inherit from Screen where I can unsubscribe EA in OnDeactivate. But if EA is subscribed inside a usercontrol then the only way is that the parent screen has to call a public method inside user control to unscubscribe (which defeats our design of each control being completely independent without public methods, probably we have to rethink our approach and make some exceptions/changes)

I am still surprised that TryClose doesn't destroy the page from the memory, learnt it experiencing it :)

Feb 16, 2011 at 2:46 AM

TryClose removed the ViewModel from the Conductor which, assuming that your ViewModel is a PerRequest instance and not a singleton, would cause the associated view to be released whenever the garbage collector kicks in. If it is a singleton, then the view will have the same lifetime of as the ViewModel (assuming that you inherit from Screen becuase Screen caches views).