I have a memory leak in my Windows (8.1) Universal project. Since my project is really big I've created a small sample project of which the only goal is to mimic the memory leak. I've tried many things to try to resolve this memory leak, but to no avail.
The situation is as follows: The app contains a list, when a button is clicked data is added to the list and when a second button is clicked the list gets cleared. I would expect to see the memory usage go up when items get added to the list, which does occur. However, when I clear the list I expect to see the memory usage to down to the level where it was before adding the items. This does not happen. Instead the memory usage is about an MB (obviously depends on how many items were added to the list) higher than it was before adding the items.
Can you help me solve this problem?
This is the code that adds items to the list:
private Custom_Observable_List leaking_items_list = new Custom_Observable_List();
private void AddItemsToList()
{
if (RESET_LIST_BEFORE_ADDING)
{
ClearItemsList();
}
if (ItemList.ItemsSource == null)
{
ItemList.ItemsSource = leaking_items_list;
}
for (int i = 0; i < AMOUNT_OF_ITEMS_TO_ADD; i++)
{
leaking_items_list.Add(new ObjectClass() { Content = ITEM_CONTENT + number_of_items_added });
number_of_items_added++;
}
}
Here ItemList is a ListView in the XAML. When the ItemSource is not set the memory leak still occurs. I suspect the leak has more to the with the ObservableCollection than with the ListView.
The code that clears the list:
private void ClearItemsList()
{
if (leaking_items_list.Count > 0)
{
leaking_items_list.Clear();
}
}
The Custom_Observable_List class:
class Custom_Observable_List : ObservableCollection<ObjectClass>
{
public Custom_Observable_List()
{
}
public Custom_Observable_List(IEnumerable<ObjectClass> collection) : base(collection)
{
}
}
I think something has to be added here so that it does not keep references to the objects that were added to it, so that Garbage Collection can actually clean everything. But I wouldn't know what to add.
And here is the class of the objects that get added to the list.
class ObjectClass : INotifyPropertyChanged
{
private string content = string.Empty;
public string Content
{
get { return content; }
set
{
if (content != value)
{
content = value;
NotifyPropertyChanged();
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(String propertyName = "")
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
I've also tried just adding strings to the list, the memory leak also occured then. I read somewhere that INotifyPropertyChanged should be implemented, that's why I created this class.
The entire project can be found here:
I tested using visual studio 2015 and its diagnostics tools. I have verified that the program crashes when after adding and clearing a couple of times, because the memory usage is too high.