【发布时间】:2012-01-24 06:10:35
【问题描述】:
我想在桌面应用程序运行时在面板中添加 1000 个图像(每个大小为 (40 到 100) KB)。首先,用户浏览所有图像并将它们加载到面板上。当它一个接一个地加载图像时,任务管理器中显示的内存使用量迅速增加,并且在一定数量的图像之后显示“内存不足异常”。我的代码中的错误在哪里?
在加载 700 张图片之前,任务管理器显示 1.05 GB 内存使用情况。 加载后任务管理器显示 2.04 GB 和 2 GB RAM 溢出
int picnumber = 0;
int numberOfImages = 12;
numberOfImages = Convert.ToInt32(textBox1.Text.ToString());
for (int i = 0; i < numberOfImages; i++)
{
GroupBox gBox = new GroupBox();
picnumber++;
////////////////////////////////
// calculate the position of the groupbox where it is placed.
if ((picnumber % 3) == 1)
{
x = initX;
}
else
{
if ((picnumber % 3) == 0)
{
x = initX + 2 * (130 + 20);
}
else
{
x = initX + 130 + 20;
}
}
///////////////////////////////////
System.Drawing.Point CurrentPoint;
CurrentPoint = panel1.AutoScrollPosition;
y = initY + ((picnumber - 1) / 3) * (130 + 20) - (Math.Abs(panel1.AutoScrollPosition.Y));
gBox.Text = picnumber.ToString();
//place the groupbox in the appropriate position.
gBox.Location = new System.Drawing.Point(x, y);
gBox.Size = new System.Drawing.Size(130, 130);
Bitmap btmap = new Bitmap(@"E:\43.jpg");
// attach the image to the groupbox
gBox.BackgroundImage = btmap;
**gBox.BackgroundImageLayout = ImageLayout.Stretch;
// add the groupbox that contains image to the panel.
panel1.Controls.Add(gBox);**
但我见过一些应用程序可以加载大量图像并且占用的内存可以忽略不计,例如“Batch Image Resizer”(http://www.jklnsoft.com/)
应用程序如何处理内存?他们遵循什么机制?
在加载 700 张图像之前,任务管理器显示 1.05 GB 内存使用量。 加载任务管理器后显示 1.06 GB
开发环境: C#.net 框架 4, 视窗XP, 视觉工作室 2010, 内存:2 GB
【问题讨论】:
-
我认为
Bitmap没有得到处理,这篇文章应该可以帮助你stackoverflow.com/questions/2808753/… -
在加载这些图像之前,您在应用中使用了 1gb..?
-
我认为结合使用 user1118321 的答案,结合 Chris Heald 的答案会很好地为您服务。
标签: c# image memory-leaks out-of-memory