Right way to dispose Image/Bitmap and PictureBox
Posted
by kornelijepetak
on Stack Overflow
See other posts from Stack Overflow
or by kornelijepetak
Published on 2010-05-11T07:21:27Z
Indexed on
2010/05/11
7:24 UTC
Read the original article
Hit count: 568
I am trying to develop a Windows Mobile 6 (in WF/C#) application. There is only one form and on the form there is only a PictureBox object. On it I draw all desired controls or whatever I want.
There are two things I am doing. Drawing custom shapes and loading bitmaps from .png files.
The next line locks the file when loading (which is an undesired scenario):
Bitmap bmp = new Bitmap("file.png");
So I am using another way to load bitmap.
public static Bitmap LoadBitmap(string path) {
using (Bitmap original = new Bitmap(path))
{
return new Bitmap(original);
}
}
This is I guess much slower, but I don't know any better way to load an image, while quickly releasing the file lock.
Now, when drawing an image there is method that I use:
public void Draw() {
Bitmap bmp = new Bitmap(240,320);
Graphics g = Graphics.FromImage(bmp);
// draw something with Graphics here.
g.Clear(Color.Black);
g.DrawImage(Images.CloseIcon, 16, 48);
g.DrawImage(Images.RefreshIcon, 46, 48);
g.FillRectangle(new SolidBrush(Color.Black), 0, 100, 240, 103);
pictureBox.Image = bmp;
}
This however seems to be some kind of a memory leak. And if I keep doing it for too long, the application eventually crashes.
Therefor, I have X questions:
1.) What is the better way for loading bitmaps from files without locking the file?
2.) What objects needs to be manually disposed in the Draw() function (and in which order) so there's no memory leak and no ObjectDisposedException throwing?
3.) If pictureBox.Image is set to bmp, like in the last line of the code, would pictureBox.Image.Dispose() dispose only resources related to maintaining the pictureBox.Image or the underlying Bitmap set to it?
© Stack Overflow or respective owner