A developer’s view

ListView may leak with ImageLists

· Read in about 5 min · (954 Words)
WinForms ListView ImageList Memory leak

Today, I encountered a problem with WinForm’s ListView imagelist. When you assign a global imagelist to the listview, then the listview will remain in memory forever. When the ListView references other objects, then these objects won’t be collected too and you might end up with a huge memory leak.

When does this occur?

ListViews won’t be collected until the associated imagelist(s) is collected, when you don’t reset the SmallImageList, LargeImageList or StateImageList properties yourself.

Why does this occur?

The LargeImageList property is implemented like this:

public ImageList LargeImageList
{
 get { return this.imageListLarge; }
 set
 {
  if (value != this.imageListLarge)
  {
   // Unsubscribe from the old image list events
   if (this.imageListLarge != null)
   {
    this.imageListLarge.RecreateHandle -= LargeImageListRecreateHandle;
    this.imageListLarge.Disposed -= DetachImageList;
    this.imageListLarge.ChangeHandle -= LargeImageListChangedHandle;
   }
 
   // Save new imagelist
   this.imageListLarge = value;
 
   // Subscribe to the new image list events
   if (value != null)
   {
    value.RecreateHandle += new EventHandler(LargeImageListRecreateHandle);
    value.Disposed += new EventHandler(DetachImageList);
    value.ChangeHandle += new EventHandler(LargeImageListChangedHandle);
   }
 
   // Update the underlying imagelist,
   // if the control is already created
   if (base.IsHandleCreated)
   {
    IntPtr imageListHandle = (value==null)?IntPtr.Zero:value.Handle;
    base.SendMessage(LVM_SETIMAGELIST, IntPtr.Zero, imageListHandle);
    if (this.AutoArrange && !this.listViewState[4])
     this.UpdateListViewItemsLocations();
   }
  }
 }
}

The implementation of SmallImageList and StateImageList are similar. You can clearly see that the ListView subscribes to the following three events of the ListView:

  • The RecreateHandle event is raised when the ImageList handle is recreated, because some of the properties have changed, that require that the underlying ImageList object to be recreated. The ListView responds to this event by setting the new ImageList to the underlying ListView object.
  • The Disposed event is raised when the ImageList is disposed. The ListView responds to this event by resetting the LargeImageList property to NULL.
  • The ChangeHandle event is an internal (and undocumented) event from the ImageList that is raised, when the ImageList is changed (i.e. adding or removing an image from the imagelist). The ListView responds to this event by setting the item images. Note that this event is only subscribed to for the LargeImageList property.

The basic idea of the garbage collector is that objects that aren’t referenced anymore are collected. As long as you reference an object it will stay alive. Subscribing to an object means that you reference the object via the event handler delegate. So, before the ListView can be collected, the reference to the imagelists should be removed by setting the properties to NULL. This will effectively unsubscribe from the three events.

When the ListView is disposed, then it should make sure that it unsubscribe from these events to prevent that the subscription keeps the ListView alive. The Dispose method is implemented like this:

protected override void Dispose(bool disposing)
{
 if (disposing)
 {
  // Reset small imagelist
  if (this.imageListSmall != null)
  {
   this.imageListSmall.Disposed -= DetachImageList;
   this.imageListSmall = null;
  }
 
  // Reset large imagelist
  if (this.imageListLarge != null)
  {
   this.imageListLarge.Disposed -= DetachImageList;
   this.imageListLarge = null;
  }
 
  // Reset state imagelist
  if (this.imageListState != null)
  {
   this.imageListState.Disposed -= DetachImageList;
   this.imageListState = null;
  }
 
  // [some other code removed]
  // ...
 
  // Call base class
  base.Dispose(disposing);
 }
}

As you can see, this method only unsubscribes from the Disposed event, but not from the imagelist’s RecreateHandle and ChangeHandle events. The garbage collector will keep the ListView alive, until the associated imagelists are collected. When you use a global imagelist, then this will never occur and each instance of the ListView that uses the imagelist will remain alive forever. Microsoft can easily fix this problem by rewriting the Dispose method like this:

protected override void Dispose(bool disposing)
{
 if (disposing)
 {
  // Reset imagelists (note that we set the property, not the attribute)
  this.ImageListSmall = null;
  this.ImageListLarge = null;
  this.ImageListState = null;
 
  // [some other code removed]
  // ...
 
  // Call base class
  base.Dispose(disposing);
 }
}

For now the only thing that you can do is to make sure you reset the imagelist yourself before your ListView is disposed.

So how about TreeViews?

A TreeView also uses an imagelist, so it would make sense that the same problem exists there. Fortunately, the TreeView is fine, because the implementation uses two special methods to subscribe and unsubscribe from the three events. The Dispose method of the TreeView calls the unsubscribe method, so the TreeView is fine.

Sample application

I have created a sample application that clearly demonstrates the problem. I needed to override the ListView class to make sure I could count its instances, but it doesn’t have any other side effects.

To illustrate the problem, start the application and press the “Create form” button. This will create a ListView and populates it with some items. When you refresh the counters you’ll see that you have one instance and one active instance (this means an instance that hasn’t been disposed yet). If you close the form and refresh the counters again, then you’ll see that there is no active instance anymore, but this is still a ListView instance. This means that the form has been disposed, but hasn’t been collected. You can try this over and over, but you will never see the number of ListView instances drop.

When you enable the “Reset imagelists when disposing” checkbox in the main form, then the properties are reset and you’ll see that the number of instances will stay in sync with the number of active instances.

Download the sample application.

Response from Microsoft

I have submitted this bug into the MSDN Managed Newsgroups and the Microsoft Feedback website. Microsoft acknowledges this to be a problem and, when it fits the schedule, it will be fixed. The recently released .NET Framework 4 Beta 1 doesn’t include the fix.

Microsoft updated the status to resolved (closed) on June 7th, 2009, but didn’t provide additional information how and when the fix will be available.

Comments