繁体   English   中英

减少动态添加的控件的内存使用情况

[英]Decrease memory usage of dynamically added controls

我有以下代码将图像从文件添加到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

我通过将源大位图复制到新的位图40x40px并调用大位图Dispose()来部分解决此问题。 但是我的应用仍然使用约50 mb的内存。 我认为问题的根源是FileDialog。 它吞噬了记忆。

问题已通过更新0解决 看它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM