I understand it is best practise to call Dispose() on instances of Pen and Brush, except if they\'ve been set to the system-predefined values (eg. System.Drawing.Brushes, Syste
There is no requirement to call Dispose
. The purpose of garbage collection is to eliminate these kinds of requirements.
One of the main purposes of IDisposable
is to allow a class to clean up unmanaged resources in resource-limited environments. If you do not call the dispose method, the unmanaged resouces of the class will be cleaned up once the object is finialized and disposed during garbage collection.
If you "must" call dispose and you do not know if the brush instance is a "system-" or a "normal-" brush then you will have to use a try...catch block.
SystemBrushes
and SystemPens
because the GDI+ Library will take care of these resources.SystemFonts
and SystemIcons
.The Remarks section of the class will make note of if there is a requirement to call the Dispose
method. If the Remarks section recommends to call the Dispose method, then I will do it.
In general, I do not call dispose on pens and brushes. If I have a graphic-intensive application or class then I will cache instances of the pens and brushes I need. I use them throughout the life of the application or class. If I didn't do this then graphics painting performance will suffer trying to create and dispose all those ojects so many times and so frequently. (Hm...now that I think about it, performance is probably why we cannot dispose of SystemBrushes and SystemPens, yet can dispose of SystemFonts and SystemIcons. Even the framework caches SystemBrushes and SystemPens.)