Almost all graphic objects are references and contain references to unmanaged code. Therefore when you do not explicitly dispose a graphic object the garbage collector may handle the managed part but omits the unmanaged part resulting in a memory leak.
Here's an example for the safest way to handle graphic objects (found @ http://stackoverflow.com/questions/1209 ... -necessary :
Code: Select all
using (Bitmap bmp = new Bitmap(100, 100))
{
using (Graphics g = Graphics.FromImage(bmp))
{
using (Pen p = new Pen(Color.FromArgb(128, Color.Blue), 1))
{
using (Brush b = new SolidBrush(Color.FromArgb(128, Color.Blue)))
{
g.FillEllipse(b, 0, 0, 99, 99);
g.FillRegion(b, pictureBox1.Region);
pictureBox1.BackColor = Color.Transparent;
pictureBox1.Image = bmp;
}
}
}
Code: Select all
using (Bitmap bmp = new Bitmap ( 100, 100 ))
using (Graphics g = Graphics.FromImage ( bmp ))
using (Pen p = new Pen ( Color.FromArgb ( 128, Color.Blue ), 1 ))
using (Brush b = new SolidBrush ( Color.FromArgb ( 128, Color.Blue ) ))
{
g.FillEllipse ( b, 0, 0, 99, 99 );
g.FillRegion ( b, pictureBox1.Region );
}
Due to th heavy use of the Draw... methodes the memory loss may sum up.