1

When programming with GDI+, do I need to stick to using pattern to all kinds of objects like Brush, Font, it can make code very cluttered.

Any suggestions?

user496949
  • 83,087
  • 147
  • 309
  • 426
  • 1
    I usually do this very strict since I had bad experiences when doing not. I use Ants Memory profiler to check whether my applications are leaking resources. – Uwe Keim Dec 28 '10 at 14:03

4 Answers4

6

Yes, you should do that for all (IDisposable) objects that you create.

The exceptions are the stock objects (Brushes.Blue, Pens.Black, e.Graphics, ...) because you don't create them.

it can make code very cluttered.

using is not as cluttered as a full try/finally. Note that you can economize the nesting:

using (Pen p = ...)
using (Brush b = ...)
{
   // draw with p and b
}

But if the choice is between cluttered code or the possibility of the program failing, is there really a choice?

H H
  • 263,252
  • 30
  • 330
  • 514
  • +1, usings seem to be under used. They keep it concise while properly disposing. – Pat Jan 27 '12 at 22:51
3

Yes, you should. These objects could contain unmanaged resources (e.g., GDI+ handles) that need to be disposed of properly. So, either use a using block or wrap everything thing in a try / finally statement where in the finally block you invoke IDisposable.Dipose.

Please see these previous answers on this topic:

What Happens if I Don't Call Dispose

Wrapping MemoryStream in a using

Community
  • 1
  • 1
jason
  • 236,483
  • 35
  • 423
  • 525
2

If you created the brush using new you should dispose of it.

If you got the brush from the Brushes collection, do not dispose of it. See the remarks section of http://msdn.microsoft.com/en-us/library/system.drawing.brushes.aspx for more info.

The same holds true of fonts, if you created it with new, dispose of it. If you got it from something else, look at the documentation to see if you should dispose if it or not.

mjcopple
  • 1,580
  • 2
  • 13
  • 19
1

Yes, you have to.

Alternative is using default brushes and fonts such as Brushes.Black, ...

Aliostad
  • 80,612
  • 21
  • 160
  • 208