开发者

Do I need to use using pattern for Font, Brush etc

When programming with GDI+, do I need to stick to using pattern to all kinds of objec开发者_运维百科ts like Brush, Font, it can make code very cluttered.

Any suggestions?


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?


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


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.


Yes, you have to.

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜