In my application I am removing some views from my backstack entry in my Windows phone application. My issue is that while removing the views the viewmodel corresponding to that view are not destroying.
I had written the cleanup in by backkeypress event. But in this case while removing the view from backstack this code block will not execute. So if we navigate b/w that page for 3-4 times the memory will increase and app will crash. How can I handle this situation?
What this problem indicates to me is that somewhere in your code you are storing a reference to your view models. For instance, are you using a factory model to construct your view models from Models? If so, when your views are destroyed, the viewmodels will stick around because the factory may still have a reference to the view models.
I suggest you do the following:
Look carefully at your code, and particularly at every place where the View Model is created, or bound to a model, or stored in an array, etc.
If you find code that stores a reference to the view model aside from the view, then when the user navigates away from the page that the view is on, make sure you add code to also clear that reference.
Once there are no objects in your app that reference the view model, the phone will automatically dispose of your view model, freeing up memory.
I would say however, if you’re using enough memory that your app is crashing because view models aren’t being destroyed, you may want to look into some performance optimization towards the end of your project. View Models in most applications should not cause that kind of memory usage unless the app is used for a very long time (viewmodels should not in the course of 3-4 pages, occupy more than the app’s alloted 90MB of memory).
Hope that helps! Try (if you can) posting some example code if you’re still stuck.