WPF Memory Usage

datatemplatelistboxmemory-managementperformancewpf

Application:

  • WPF Application consisting of a textbox on top and a listbox below
  • Users type a string in the TextBox to find employees, and search results are displayed in the ListBox
  • ListBox uses DataTemplates to display elements (shows employee name, department, phone and a thumbnail picture.)

Implementation:

  • At application startup I query the database and retrieve all employees and related information to be shown in the ListBox. This is kept in memory the entire time.
  • After application startup, all the searchable data is in memory and searches are virtually instantaneous. All searches are performed on the data already in memory.
  • Search results are displayed in the ListBox using DataTemplates. Thumbnail picture, name, phone, department, etc, are shown in each ListBox item.

Problem:

  • At startup the memory usage is about 200MB.
  • As data is changed in the listbox, either via a new search or a simply scrolling down the listbox, memory consumption increases.
  • When users scroll down the listbox slowly, memory increases faster. As you scroll it up and down memory quickly reaches 1GB.

There are is no code creating controls manually – everything is done via data binding.

Why am I seeing this behavior? What can I do to fix it? Please help!

UPDATE:
I figured out that the problem is not a memory leak. The issue here is that the listbox is creating objects to display the images of the employee and is not releasing for the garbage collector after the listboxitem gets out of the window. The CleanUpVirtualizedItem event occurs as I expected but the memory is still not released. Any ideas?

Best Answer

At the risk of being glib, you have a memory leak. Why not try a tool like ANTS* to track it down. They have a free trial, I've never used it but it has a good reputation.

*Other profiling tools are available.

If you don't want to get to grips with another tool, you can try something like incrementing a static member every time a class is created and decrementing it every time an instance is disposed. This will help you track down instances that are not be destroyed properly.