tags:

views:

195

answers:

3

How expensive is it to create gdi brushes and pens? Should I create them on an add needed basis and wrap them in a using so they are disposed quickly, or should I create a static class similar to System.Drawing.Brushes class?

+2  A: 

I've encountered exceptions when trying to custom draw images in a web application under load with a static brush.

I don't know the technical reasons, but I think Brushes and Pens are not thread safe, so I would create them as needed in a thread-safe manner and dispose of them within that scope, probably with a using.

Greg
+1  A: 

For our configurable GUI we figured we'd try just putting them in a "using" (re-create whenever required) when drawing our controls and figured we'd optimise if required.

It hasn't been required.

This is WinForm on WinCE which generally means its good at showing up things that might be slightly slow on the desktop (reflection feels much more expensive on WinCE for example) so unless you are doing some insane image manipulation on desktop that requires mucho perf then I think you should be fine creating them as and when required.

IIRC using the Brushes. collection in the GDI might be an option as this ensures they get cached and disposed at the end although i'm not sure about thread safety there.

Quibblesome
+4  A: 

IMO, they're efficient enough that you should usually not create long-lived instances that are used over several method calls, but inefficient enough that you should create each one only once within a particular method, instead of creating a new one each time you need to draw something.

In other words, don't store a custom brush in your class that you use to paint your text on every OnPaint call, but also don't create a new brush for every line of text you draw within that OnPaint call, either.

P Daddy