Recent work has often been asked how to reduce the use of WP memory, and then again began to study the memory problem, first found longlistselector use a common problem:
Overview
If you set the ItemsSource of the Longlistselector control to a ObservableCollection collection in ViewModel, you should pay attention to the memory problem.
The problem arises
The following demo simulates the following scenario Itemsource binding to a static observablecollection outside of the page. So if our program structure is
Mainpage->loginpage, switching back and forth between MainPage and LoginPage can lead to multiple loginpage in memory that cannot be interpreted.
Namespace Feinno.Beside.View.Pages
{public
class BindingSource
{public
static observablecollection<object> Collection =
new observablecollection<object> ();
}
public partial class Loginpage:phoneapplicationpage
{public
loginpage ()
{
InitializeComponent () ;
List is the Longlistselector list defined in XAML
. ItemsSource = bindingsource.collection;
Debug. WriteLine ("Initialze page!! Hashcode = "+ GetHashCode ());
}
~loginpage ()
{
Debug. WriteLine ("Uninitialze page!! Hashcode = "+ GetHashCode ());}}}
The normal state (no memory issue) is printed as follows: The above code is printed as follows:
Page can be destroyed in time.
As you can see, when you switch the page back and forth, the previous page is not released, but it is in memory.
See more highlights of this column: http://www.bianceng.cnhttp://www.bianceng.cn/OS/extra/
Cause
The author tries to use the listbox to execute the same code, and this does not occur, so the analysis is a problem with Windows Phone 8 's new longlistselector.
The specific reason is because ObservableCollection exposes the CollectionChanged interface to ObservableCollection Longlistselector Itemsource, Longlistselector through this interface to monitor the collection of changes in the list, because the use of strong events, then ObservableCollection will hold a reference to Longlistselector, so that after leaving the page, When GC reclaims resources, it is thought that LoginPage is still in use, leading to results that we do not want to see.
Solutions
Set the Itemsource to NULL when the page is left when there is a itemsource setting for the similar scenario above
In-depth analysis
So what if the controls in the page binding to the binding source in the code?
By writing demo analysis and access to relevant information, the author draws the conclusion:
1, Longlistselector.itemsource (ListBox without this problem) if binding to ObservableCollection, the result is consistent with the above, page cannot be released.
2, other attributes of the binding will not cause the above problems.