I created a simple example to test the image control's memory handling. On a dockpanel there are two buttons ("Load" and "Reset") and an image control. In the code behind, the event handlers of the buttons look like this:
private void LoadButton_Click(object sender, RoutedEventArgs e)
{
var dlg = new OpenFileDialog
{
Title = "Open image file",
DefaultExt = ".tif",
Filter = "",
Multiselect = false,
InitialDirectory = "D:\\testimages"
};
dlg.ShowDialog();
string file = dlg.FileName;
if (!string.IsNullOrEmpty(file))
{
if (this.img.Source != null)
{
this.img.Source = null;
this.img.UpdateLayout();
GC.Collect();
}
var bi = new BitmapImage();
bi.BeginInit();
bi.CacheOption = BitmapCacheOption.OnLoad;
bi.UriSource = new Uri(file);
bi.EndInit();
bi.Freeze();
this.img.Source = bi;
}
else
{
this.img.Source = null;
this.img.UpdateLayout();
GC.Collect();
}
}
private void ResetButton_Click(object sender, RoutedEventArgs e)
{
this.img.Source = null;
this.img.UpdateLayout();
GC.Collect();
}
When I load the first image, the memory usage increases. Hitting the Reset-button, the memory is released correctly. So far this looks like correct behaviour. But if I do not "reset", but load another image, the memory usage increases. "Reset" does only release the memory of the latest image. How can I make sure, that the memory of previously loaded images gets released when loading the next image?
The images I use are app. 4000 x 1000 px with a resolution of 300dpi.