I have WPF window with Grid control imageGrid
and button buttonRefresh
. The code is for testing purposes and may look a bit strange. Window code:
public partial class MainWindow : Window
{
const int gridWidth = 10;
const int gridHeight = 20;
const int cellWidth = 100;
const int cellHeight = 100;
const int bitmapWidth = 1024;
const int bitmapHeight = 1024;
WriteableBitmap[,] bitmaps;
public MainWindow()
{
InitializeComponent();
buttonRefresh.Click += new RoutedEventHandler(buttonRefresh_Click);
FillGrid();
}
void buttonRefresh_Click(object sender, RoutedEventArgs e)
{
FillGrid();
}
void FillGrid()
{
ClearGrid();
CreateBitmaps();
InitGrid();
}
void ClearGrid()
{
imageGrid.Children.Clear();
imageGrid.RowDefinitions.Clear();
imageGrid.ColumnDefinitions.Clear();
bitmaps = null;
}
void InitGrid()
{
for (int i = 0; i < gridWidth; ++i)
{
ColumnDefinition coldef = new ColumnDefinition();
coldef.Width = GridLength.Auto;
imageGrid.ColumnDefinitions.Add(coldef);
}
for (int i = 0; i < gridHeight; ++i)
{
RowDefinition rowdef = new RowDefinition();
rowdef.Height = GridLength.Auto;
imageGrid.RowDefinitions.Add(rowdef);
}
for (int y = 0; y < gridHeight; ++y)
{
for (int x = 0; x < gridWidth; ++x)
{
Image image = new Image();
image.Width = cellWidth;
image.Height = cellHeight;
image.Margin = new System.Windows.Thickness(2);
image.Source = bitmaps[y, x];
imageGrid.Children.Add(image);
Grid.SetRow(image, y);
Grid.SetColumn(image, x);
}
}
}
void CreateBitmaps()
{
bitmaps = new WriteableBitmap[gridHeight, gridWidth];
byte[] pixels = new byte[bitmapWidth * bitmapHeight];
Int32Rect rect = new Int32Rect(0, 0, bitmapWidth, bitmapHeight);
for (int y = 0; y < gridHeight; ++y)
{
for (int x = 0; x < gridWidth; ++x)
{
bitmaps[y, x] = new WriteableBitmap(bitmapWidth, bitmapHeight, 96, 96, PixelFormats.Gray8, null);
byte b = (byte)((10 * (x + 1) * (y + 1)) % 256);
for (int n = 0; n < bitmapWidth * bitmapHeight; ++n)
{
pixels[n] = b;
}
bitmaps[y, x].WritePixels(rect, pixels, bitmapWidth, 0);
}
}
}
}
When this program starts, FillGrid
function runs successfully. When Refresh button is clicked, FillGrid
is executed again, and this time new WriteableBitmap
line throws OutOfMemoryException
. I think that ClearGrid
function doesn't release all resources, and bitmaps
array is not destroyed yet. What is the problem in this code?
XAML:
<Window x:Class="Client.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Grid and DirectX" Height="600" Width="800">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Button HorizontalAlignment="Center" Padding="20 2" Margin="0 2" Name="buttonRefresh">
Refresh
</Button>
<ScrollViewer Grid.Row="1" HorizontalScrollBarVisibility="Auto">
<Grid Name="imageGrid"/>
</ScrollViewer>
</Grid>
</Window>