我有WPF窗口與網格控制imageGrid
和按鈕buttonRefresh
。該代碼僅用於測試目的,可能看起來有點奇怪。窗口代碼:網格清理代碼
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:
<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()不起作用?」。 –