Grid 컨트롤 imageGrid
및 버튼 buttonRefresh
이있는 WPF 창이 있습니다. 이 코드는 테스트 용이며 약간 이상하게 보일 수 있습니다. 창 코드 :그리드 정리 코드
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);
}
}
}
}
이 프로그램을 시작하면 FillGrid
함수가 성공적으로 실행됩니다. 새로 고침 버튼을 클릭하면 FillGrid
이 다시 실행되고 이번에는 new WriteableBitmap
라인이 OutOfMemoryException
을 던졌습니다. 나는 ClearGrid
함수가 모든 리소스를 해제하지 않으며, bitmaps
배열이 아직 파괴되지 않았다고 생각합니다. 이 코드의 문제점은 무엇입니까?
XAML은 : 귀하의 경우 WriteableBitmap
에서 메모리 누수를 만들기 때문에
<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>
@Alex Farber : 제 질문에 대한 편집 - 왜 GC.Collect()가 도움이되지 않습니까? '를 참조하십시오. –