Normally when I override the OnPaint method, I create pens and brushes, etc inside it and then dispose them.
I also read somewhere that instead of recreating these pens and brushes, etc to create them once as static members, and then dispose them once when the form is closed, etc.
Is this a better practice?
Is there a better way for this?
I can assume that since OnPaint is called 1000s (?) of times, that would create a lot of work for the GC compared to creating them only once.
If the brushes and pens don't change, it's certainly better to create them once and reuse them. Note, however, that if your control might be used on multiple threads (which is very unlikely), you should either make them ThreadStatic
(and initialize on first use per thread) or make them instance members (and dispose them in your control's Dispose
override); otherwise, you'll get unreproducable GDI+ errors, as GDI+ objects cannot be used on multiple threads at once. The same is true for images.
If the they do change (for example, if you use gradient brushes which depend on the control's size), you might still want to store them in instance fields, and recreate them when the control's size (or whatever) changes.
Note, by the way, that if you use normal colors, you can use the static Brushes
and Pens
classes, which contain static brushes and pens for all of .Net's built-in colors, and SystemBrushes
and SystemPens
for system colors.
I read an interesting article last month which suggested doing all of your painting onto a separate BufferedGraphics object, and have the on_paint method do a straight copy from that to your control's graphics object.
That way, the on-paint is faster, and you only update your BufferedGraphics when something significant changes (i.e. a line moves or text changes).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With