1

I am making an album application with windows forms and I have a problem that I can't solve. First of all I have a form where I create a TableLayoutPanel. After that I create a method where I generate the same amount of picture boxes as the amount of the images in the directory which I have opened. The problem occurs when I am trying to dispose the image which I load in the picturebox because I need to free its memory. Here is the code of the method:

public void createPictureBoxes()
    {
        Image loadedImage;
        int imageCounter = 0;
        for (int i = 0; i < rowCounter; i++)
            for(int p = 0; p < imagesTable.ColumnCount; p++)
            {
                PictureBox pb = new PictureBox();
                pb.SizeMode = PictureBoxSizeMode.Zoom;
                pb.Width = imagesTable.GetColumnWidths()[p];
                pb.Height = imagesTable.GetRowHeights()[i];
                pb.Click += new EventHandler(enlargeThumbnail);
                try
                {
                    loadedImage = Image.FromFile(images[imageCounter++]);
                    pb.Image = loadedImage;
                    loadedImage.Dispose();
                    imagesTable.Controls.Add(pb);
                    loadedImage.Dispose();
                }
                catch (IndexOutOfRangeException)
                {
                    break;
                }
            }
    }

The program throws an ArgumentException on method Show() of the form telling me that the argument is not valid. Without the dispose method all works fine but if i try to load a large amount of images the program uses gigabytes of memory. I suppose that it is not right to dispose the image memory that way, but I can't come out with another idea. If someone could help I would be very grateful

4

2 回答 2

3

两个问题:您要处理两次,而且只要父控件容器需要使用它,您将无法处理图像控件。当表单被释放时,它将导致所有属于其容器的控件都被释放。

因此,与其尝试处理两次,不如根本不处理(这里就是)!

于 2013-04-24T07:30:47.460 回答
2

您无法在显示图像时对其进行处置。如果这样做,表单将无法显示它。

当您将实例分配给属性时,它PictureBox不会复制实例。它保留了实例,因此在您从图片框中删除图像之前,您无法处置它。ImageImage

于 2013-04-24T07:33:26.340 回答