Is it important to dispose SolidBrush and Pen?

Posted by Joe on Stack Overflow See other posts from Stack Overflow or by Joe
Published on 2009-11-30T10:51:06Z Indexed on 2010/04/09 21:23 UTC
Read the original article Hit count: 278

Filed under:
|
|

I recently came across this VerticalLabel control on CodeProject.

I notice that the OnPaint method creates but doesn't dispose Pen and SolidBrush objects.

Does this matter, and if so how can I demonstrate whatever problems it can cause?

EDIT

This isn't a question about the IDisposable pattern in general. I understand that callers should normally call Dispose on any class that implements IDisposable.

What I want to know is what problems (if any) can be expected when GDI+ object are not disposed as in the above example. It's clear that, in the linked example, OnPaint may be called many times before the garbage collector kicks in, so there's the potential to run out of handles.

However I suspect that GDI+ internally reuses handles in some circumstances (for example if you use a pen of a specific color from the Pens class, it is cached and reused).

What I'm trying to understand is whether code like that in the linked example will be able to get away with neglecting to call Dispose.

And if not, to see a sample that demonstrated what problems it can cause.

I should add that I have very often (including the OnPaint documentation on MSDN) seen WinForms code samples that fail to dispose GDI+ objects.

© Stack Overflow or respective owner

Related posts about .NET

Related posts about winforms