المساعد الشخصي الرقمي

مشاهدة النسخة كاملة : To Dispose() or not Dispose(), that is the question.



C# Programming
05-06-2009, 03:23 AM
Okay, I’m confused on what to Dispose and when. Below is a subroutine called from a loop. First time through it is okay, the second time through it throws a System.Exception “Parameter is not valid” on the DrawString line. But if I remove all the Dispose commands at the bottom I can call this subroutine a dozen times without error.

Obviously in this instance I can just remove the Dispose commands and move on but I want to understand when I should or shouldn’t call Dispose. (After all I might be missing some Dispose calls elsewhere in my program.)


private void DrawRotatedText(Graphics Canvas, string text, Rectangle DestRect)
{
//Create temp workspace
Bitmap bmp = new Bitmap(500, 500, PixelFormat.Format64bppArgb);
Graphics g = Graphics.FromImage(bmp);
g.Clear(Color.White);

//Write on it
Font font = new Font("Arial", 12, FontStyle.Regular, GraphicsUnit.Pixel);
Brush brush = Brushes.Black;
StringFormat stringFormat = new StringFormat();
stringFormat.Alignment = StringAlignment.Center;
stringFormat.LineAlignment = StringAlignment.Center;
g.DrawString(text, font, brush, (bmp.Width / 2), (bmp.Height / 2), stringFormat);

//Rotate image here
Bitmap bmp2 = Rotator.RotateImage(bmp, (360 - 45));

// Set the transparency color key based on the upper-left pixel of the image.
ImageAttributes attr = new ImageAttributes();
attr.SetColorKey(bmp.GetPixel(0, 0), bmp.GetPixel(0, 0));

// Draw the image using the image attributes.
Rectangle SrcRect = new Rectangle((bmp2.Width / 2) - (DestRect.Width / 2),
(bmp2.Height / 2) - (DestRect.Height / 2), DestRect.Width, DestRect.Height);
Canvas.DrawImage(bmp2, DestRect, SrcRect.Left, SrcRect.Top, SrcRect.Width,
SrcRect.Height, GraphicsUnit.Pixel, attr);

//Tidy up
bmp.Dispose();
font.Dispose();
brush.Dispose();
stringFormat.Dispose();
bmp2.Dispose();
attr.Dispose();
g.Dispose();
}