I have the same kind of app, with the next/previous picture buttons. And I had exactly the same memory leak, which has driven me mad.
I still haven’t been able to find the root cause, but I’ve managed to bypass it with a ugly hack. When displaying the next picture, I force the old image source to load an invalid picture, thus freeing the memory. I don’t understand why removing all references and calling the garbage collector isn’t enough, there must be another reference kept internally somewhere.
Anyway, here is the hack:
private void DisposeImage(BitmapImage image)
{
if (image != null)
{
try
{
using (var ms = new MemoryStream(new byte[] { 0x0 }))
{
image.SetSource(ms);
}
}
catch (Exception)
{
}
}
}
You can call it for instance in your RefreshImage
method:
private void RefreshImage()
{
BitmapImage image = ImageHolder.Source as BitmapImage;
ImageHolder.Source = null;
DisposeImage(image);
ImageHolder.Source = new BitmapImage(new Uri("000\\image" + (pageNum + 1).ToString("D3") + ".jpg", UriKind.Relative));
RefreshTextData();
}
Kinda ashamed to use that, but at least it seems to work.