Detailed solution to the.NET BitmapImage memory release problem

  • 2020-06-07 04:22:53
  • OfStack

Most of the code found on the Internet is written using MemoryStream:


new Thread(new ThreadStart(() => {
    var bitmap = new BitmapImage();
    bitmap.BeginInit();
    using (var stream = new MemoryStream(File.ReadAllBytes(...))) {
        bitmap.StreamSource = stream;
        bitmap.CacheOption = BitmapCacheOption.OnLoad;
        bitmap.EndInit();
        bitmap.Freeze();
    }
    this.Dispatcher.Invoke((Action)delegate {
        Image1.Source = bitmap;
    });
})).Start();

Issue came today, when I set up a DecodeWidth for 100 load 1000 images, it's supposed to maintain a 100 x 100 said memory 1000 images, but in fact he retained the original image in memory until BitmapImage recycled when released, it makes me very embarrassed, in other words using (MemoryStream) doesn't really follow we expect to release the Buffer MemoryStream, that how to release?
In fact, the simplest way is to simply abandon MemoryStream and switch to FileStream, as follows:

using (var stream = new FileStream(path, FileMode.Open)) {
    image.BeginInit();
    image.StreamSource = stream;
    image.DecodePixelWidth = 100;
    image.CacheOption = BitmapCacheOption.OnLoad;
    image.EndInit();
    image.Freeze();
}


Related articles: