Dispose image in WPF in Listbox (memory leak)

I have a ListBox with a bunch of images in it (made using datatemplate). Images are created by setting the source of the elements:

<Image x:Name="ItemImage" Source="{Binding ImageUrl}"/> 

and then they are cleared using the Items.Clear () method. New images are added using the Items.Add method in the list.

However, memory usage just starts to move up and up. These are the same 300 or so small images that are displayed, but the memory does not seem to be freed. The application begins to use about 40 megabytes and quickly rises to 700 megabytes. How to free the memory that all these images use?

EDIT . One thing I forgot to mention is that images (about 4-5 thousand in size) are downloaded over the network. Is caching somehow responsible for this? A display of 12 images plays out about 10 megabytes of memory, which is about 100X files.

+5
source share
2 answers

If you are not doing anything unusual when downloading images (for example, using image boot loaders or something like that), GC should destroy them for you when nothing else refers to them.

Do you hold on to data links anywhere? Remember that events and event handlers can sometimes β€œcheat” the garbage collector, thinking that the object is still in use:

MyObject obj = new MyObject();
obj.TheEvent += new EventHandler(MyHandler);
obj = null;
// Now you might think that obj is set for collection but it 
// (probably - I don't have access to MS' .NET source code) isn't 
// since we're still listening to events from it.

, , , , , .

, , AQTime , .

, , , .

+4

, ?

( : .)

, . IValueConverter, , BitmapImage DecodePixelWidth DecodePixelHeight. , ...

class PathToThumbnailConverter : IValueConverter {
    public int DecodeWidth {
        get;
        set;
    }

    public PathToThumbnailConverter() {
        DecodeWidth = 200;
    }

    public object Convert( object value, Type targetType, object parameter, System.Globalization.CultureInfo culture ) {
        var path = value as string;

        if ( !string.IsNullOrEmpty( path ) ) {

            FileInfo info = new FileInfo( path );

            if ( info.Exists && info.Length > 0 ) {
                BitmapImage bi = new BitmapImage();

                bi.BeginInit();
                bi.DecodePixelWidth = DecodeWidth;
                bi.CacheOption = BitmapCacheOption.OnLoad;
                bi.UriSource = new Uri( info.FullName );
                bi.EndInit();

                return bi;
            }
        }

        return null;
    }

    public object ConvertBack( object value, Type targetType, object parameter, System.Globalization.CultureInfo culture ) {
        throw new NotImplementedException();
    }

}

IsAsync=True Binding, .

+4

All Articles