Click here to Skip to main content
15,887,083 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi All,

I am doing an R&D with Dispose. I have a doubt in case of Forms on disposing the image resource.

C#
namespace DisposeTry
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
 
        private void Form1_Load(object sender, EventArgs e)
        {
            Image mimg = new Bitmap("repository.png"))
            image1.Image = mimg;
        }
    }
}


Please clarify what is the right way.

What I have tried:

C#
namespace DisposeTry
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            using (Image mimg = new Bitmap("repository.png"))
                image1.Image = mimg;   // Obvious error
        }
    }
}
Posted
Updated 6-Aug-16 0:24am

1 solution

You can't Dispose of anything while it's in use - that's just silly - and an Image in a PictureBox or similar control is in use as long as the PictureBox could potentially be seen.
If you create an Image, and it is needed for the lifetime of the Form (or else why create it in the Load event) then you can Dispose it in the FormClosed event, or when it it replaced by another image for display.
If the Form is your main form, then you don't need to do anything in the FormClosed event handler, it will be disposed for you when the form closes as that terminates the application.
 
Share this answer
 
Comments
Priya-Kiko 6-Aug-16 6:33am    
Thanks for the response. So it simply means to keep track of the images or such resources created in the form (not necessarily in form load) and Dispose them in the dispose event or close event right ?
OriginalGriff 6-Aug-16 6:49am    
Basically, yes. But do remember that when you "keep track" of things, that counts as a reference, so you need to get rid of the "tracks" as well when you dispose things.
For the example you give, the PictureBox provides the tracking mechanism, and all you need to do is Dispose the Image just before you replace it with a new one.

And as I said: if the app is closing, that will dispose everything for you anyway.
Priya-Kiko 6-Aug-16 7:51am    
Thank you.
OriginalGriff 6-Aug-16 8:18am    
You're welcome!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900