0

I am filling a Listbox with different images:

ListBoxItem itm = new ListBoxItem();
var bitmap = new BitmapImage();
var img = new Image();
var stream = File.OpenRead(e.FullPath); 
bitmap.BeginInit();
bitmap.CacheOption = BitmapCacheOption.OnLoad;
bitmap.StreamSource = stream;
bitmap.EndInit();
stream.Close();
stream.Dispose();
img.Source = bitmap;
itm.Content = img;
galerielb.Items.Insert(0, itm);
if (galerielb.Items.Count > 9)                      
     galerielb.Items.RemoveAt(galerielb.Items.Count - 1);

The last Line does not free up the memory used by the image? How can I free it in the above code?

daniel
  • 34,281
  • 39
  • 104
  • 158
  • 2
    You shouldn't need to worry about such things with C#. Let the garbage collector do its thing. Is there a reason you need it freed immediately? – itsme86 Jul 02 '19 at 16:18
  • the GC does nothing here? I have quite big images and after some time my app crashes because of this – daniel Jul 02 '19 at 16:18
  • 1
    As a note, you do usually not create UI elements in code behind. The Image element should be inside the ItemTemplate of the ListBox, while the ListBoxItem would be automatically created by the ListBox's ItemContainerGenerator. Just bind the ListBox's ItemsSource to a collection of path strings. See e.g. here: https://stackoverflow.com/a/15601198/1136211 – Clemens Jul 02 '19 at 16:20
  • Anyway, for saving memory `bitmap.Freeze()` would help. You could also set `DecodePixelWidth` or `DecodePixelHeight` to load smaller bitmaps. In an MVVM approach with control over bitmap size and freezing, you would bind the ItemsSource to an `ObservableCollection`, which you populate with your BitmapImages. – Clemens Jul 02 '19 at 16:26
  • seems that bitmap.Freeze() help a bit – daniel Jul 02 '19 at 16:52
  • Why would calling `RemoveAt` "free up memory"? C# is a managed programming language. The garbage collector releases memory back to the operating system as required. Exactly when and how it does this is nondeterministic. The only thing you should care about is to not keep references to objects in memory that you no longer use. The GC will take care of the rest. There is a great chance that it won't release any memory immediately, despite the fact that your process doesn't currently uses or needs it. – mm8 Jul 03 '19 at 09:54

0 Answers0