Should I create new Pens/Brushes per Paint request or keep them throughout the application lifecycle?

后端 未结 5 2177
北海茫月
北海茫月 2021-02-19 02:33

I have an application that does a lot of drawing, let\'s pretend it\'s a Viso-like application. It has objects that have multiple sub-objects that are drawn, things can

5条回答
  •  长发绾君心
    2021-02-19 03:20

    Okay this is an old question, it is probably new for some and has a simple and intuitive solution followed by a detailed explanation.

    "Should I hold on to paint resources, like pens and brushes, longer than what is required to preform my painting operation", question is rephrased? The answer is no, you should not in that very context; but why, what does that mean?

    When you are painting to a graphics object you are using memory intensive resources for each paint object you create, be it a pen, brush, path, matrix and so on.

    Yes, do create pens, create brushes etc. for painting and do myPen.dispose() and immediately following do release all object references to the disposed object by setting that object tree to null such as (myPen = null;) this allows the garbage collector to release unmanaged memory held by these objects without having to wait for the call to object finalize(). See: Garbage collection for more information about how garbage collection works in C#.

    Creating too many of these IDisposable class objects and not releasing these objects when finished "Using" them can have serious consequences to your program's operation such as causing possible stack and heap memory exceptions, causing increased CPU usage by having to sort through unnecessary quantities of objects potentially causing slow performance and even a runtime crash if left unchecked. See about the Stack and Heap for more information.

    Moral of the story release resources you no longer require; if you must retain resources, bench test the potential effects on performance when you "hold on to resources" hopefully avoiding negative consequences.

    Rule of thumb: At the out most, ensure all resources are released upon exiting your "paint event" routine. Preferably, When each of your paint event methods finish so too should any resources implicitly created by that method. Penalty, any object references *passed to those methods like pens and brushes etc. will be held until base object finalize is called which is longer than necessary and can be considered a memory leak in the general terms of the definition. *Pass too many references equals unusable memory for a longer period than what probably is expected or assumed.

    Note: Cautiously pass object references like pens and brushes to methods and if doing so implement an IDisposable interface at a class level to perform your painting. Your homework just got more expensive and recommend checking out the IDisposable interface.

    Happy painting!

提交回复
热议问题