我有以下代码将文件中的图像添加到Windows窗体面板控件。
private void AddImageButton_Click(object sender, EventArgs e)
{
if (AddImageFileDialog.ShowDialog() == DialogResult.OK)
{
using (FileStream stream = new FileStream(AddImageFileDialog.FileName, FileMode.Open, FileAccess.Read))
using (BinaryReader reader = new BinaryReader(stream))
{
var memoryStream = new MemoryStream(reader.ReadBytes((int)stream.Length));
AddImage(new Bitmap(memoryStream));
}
}
}
private void AddImage(Bitmap image)
{
var pictureBox = new PictureBox();
pictureBox.Name = Guid.NewGuid().ToString();
pictureBox.Image = image;
pictureBox.Width = 40;
pictureBox.Height = 40;
pictureBox.SizeMode = PictureBoxSizeMode.Zoom;
pictureBox.Click += OnImageClicked;
ImagePanel.Controls.Add(pictureBox);
}
1)当我运行我的应用程序时,内存使用量约为18 MB。
2)当我打开FileDialog窗口时,内存使用量约为50MB。
3)随着我添加的每个图像,内存增加2-10MB。
因此,如果我添加20个图像,内存使用量超过100MB。
我觉得我做错了什么,但我无法得到什么。你能帮我找出我的错误并解释问题存在的原因吗?
更新0
我通过将源大的Bitmap复制到新的Bitmap 40x40px并调用大的Bitmap Dispose()来部分解决问题。但我的应用仍然使用大约50 MB的内存。我认为问题的根源是FileDialog。它吃了记忆。
使用Update 0修复了问题。查看它。