Avoiding disposing system-defined Pen and Brush instances

后端 未结 8 1980
离开以前
离开以前 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:58

    I could be wrong but I think you can assume that the lifetime (and the disposal) of the predefined brushes and pens is not your app's responsibility and will be handled by the system.

    In short: don't call Dispose on the predefined stuff. :)

    0 讨论(0)
  • 2021-02-14 01:59

    First of all, you always should Dispose of brushes when you can and not leave it up to the garbage collector. While GDI will eventually get around to taking care of that stuff (assuming the library gets shut down properly), there's no telling when that may be. In fact, my understanding is that brush handles stick around for the long-term. Over the course of a long-running application, you're looking at a de facto memory leak. Sure, in a small application that won't run for long, or in one that only rarely creates brushes, you can let the system handle it, but that strikes me as sloppy.

    As a general rule, whenever I create a brush I do so in a using statement. That automatically calls dispose on the brush without having to worry about it. As an added bonus, since you create the brush inside the statement you know that it's not a predefined brush. Any time you create and use a non-predefined brush, wrap the block in a using and you don't have to worry about it at all. In fact, you don't even need to explicitly call Dispose, since the block will do so even in the case of an exception.

    0 讨论(0)
提交回复
热议问题