I'm seeing a huge memory leak in a program I'm building using WPF. I've written a small example app which seems to replicate this issue on a smaller scale.
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
images = Directory.GetFiles("C:\\Photos", "*.jpg",
SearchOption.TopDirectoryOnly);
foreach (string image in images)
{
Window1 window = new Window1(image);
window.Show();
window.Close();
}
}
}
The Window1 XAML . . .
<Window x:Class="WpfApplication1.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1"
AllowsTransparency="True"
WindowStyle="None"
Background="White"
Opacity="1.0"
<Grid>
<Image Name="pb_Image"/>
</Grid>
. . . and the Window1 code
public Window1(string image)
{
InitializeComponent();
BitmapImage bi = new BitmapImage(new Uri(image, UriKind.Absolute));
bi.Freeze();
pb_Image.Source = bi;
pb_Image.Height = bi.Height;
pb_Image.Width = bi.Width;
}
It repeatedly shows and then closes a window which contains a BitmapImage
however an "out of memory exception" occurs very quickly so I'm obviously doing something wrong and hoping someone can point it out!
* Update *
After playing around for a while I've isolated the issue, this causes a memory leak:
foreach (string image in images)
{
Window1 window = new Window1(image);
window.Show();
window.Close();
}
and this doesn't
foreach (string image in images)
{
Window1 window = new Window1("C:\\Photos\\photo1.jpg");
window.Show();
window.Close();
}
Puzzling - any ideas???