Avoiding disposing system-defined Pen and Brush instances

后端 未结 8 2004
离开以前
离开以前 2021-02-14 01:07

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

8条回答
  •  别那么骄傲
    2021-02-14 01:55

    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.

    • It is not needed to call dispose on SystemBrushes and SystemPens because the GDI+ Library will take care of these resources.
    • Okay to dispose of 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.)

提交回复
热议问题