Search code examples
c#wpfmemory-leaksbitmapimage

Out of Memory with BitmapImage


I'm trying to developp an app to take and print photos with Visual Studio 2013.

The app is divide in 2 project :

  • First the client, it take 4 photos and send their pathfiles.

  • The second is the server. When there is a connection, he show the 4 photos. Then the user can choose a frame, a quantity and print his photos.

There is a problem with the loading:

            BitmapImage _img1 = new BitmapImage();
            _img1.BeginInit();
            _img1.CacheOption = BitmapCacheOption.OnLoad;
            _img1.UriSource = new Uri(_images[0]);
            _img1.EndInit();
            img1.Source = _img1;

            BitmapImage _img2 = new BitmapImage();
            _img2.BeginInit();
            _img2.CacheOption = BitmapCacheOption.OnLoad;
            _img2.UriSource = new Uri(_images[1]);
            _img2.EndInit();
            img2.Source = _img2;

            BitmapImage _img3 = new BitmapImage();
            _img3.BeginInit();
            _img3.CacheOption = BitmapCacheOption.OnLoad;
            _img3.UriSource = new Uri(_images[2]);
            _img3.EndInit();
            img3.Source = _img3;

            BitmapImage _img4 = new BitmapImage();
            _img4.BeginInit();
            _img3.CacheOption = BitmapCacheOption.OnLoad;
            _img4.UriSource = new Uri(_images[3]);
            _img4.EndInit();
            img4.Source = _img4;

I've try with "BitmapCacheOption.OnDemand". When the program start, memory consumption is 3Go. After few minutes, it increase to 6Go.

When the outofmemoryexception is thrown, it comes to PresentationCore.dll

I've looking ofr the consumption, and at each loop of the program, the comsumption increase of 0,4Go.

WIthout show the photos, the app is stable.

I've try with Bitmap and BitmapImage, GC.Collect and DeleteObject of gdi32.dll, the problem is the same.

Is there a way to dispose all the resources?

Sorry for my english


Solution

  • You are caching the whole bitmap in memory - BitmapCacheOption.OnLoad. Try using None or OnDemand instead of OnLoad.