Reputation: 23
I am currently using the paint event on a form to draw an image onto the screen. (Think a background image) and some rectangles on top of this image.
private void MainWindow_Paint(object sender, PaintEventArgs e)
{
e.Graphics.Clear(Color.CornflowerBlue);
e.Graphics.DrawImage(Image.FromFile(m_Directory + @"\Images\" + BackgroundText), m_Screen);
e.Graphics.FillRectangle(BGBrush, new Rectangle(X, Y, Width, Height));
e.Graphics.DrawString(Text, Settings.TextFont, Other.Settings.TextBrush, new Rectangle(X, Y + 2, Width, Height));
}
The page is being repainted very often (almost on every mouse move event) and is causing huge amounts of memory to be used. Getting to 1,500,000k before it stops drawing to the form and displays the white background with red cross on the picture for a failed paint.
I am at a slight loss as to how it is running off so badly. I am new to drawing with the paint event so any help will be much appreciated!
Upvotes: 2
Views: 954
Reputation: 11396
Image
is IDisposable
, so you should execute the DrawImage call within a "using" block, to ensure the Image is disposed.
But most importantly, I would reconsider doing heavy IO operations in a Paint event. Possibly have the images loaded ahead of time, to have the Paint event only worry about drawing. You are currently loading the same image hundreds of times.
Upvotes: 1
Reputation: 5895
I think that if your UI thread is being use constantly, the finalizer will be blocked. The objects might be garbage collected, but disposeable object would be added to the finalizer queue. The finalizer runs in the UI thread, so if your UI thread is busy, dispose wont be called. Graphics objects usually wrap an unmanaged object and that object needs to be cleaned up with dispose().
I would manually dispose all of your graphics related objects when you are done painting.
Upvotes: 0