Avoiding disposing system-defined Pen and Brush instances

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

提交回复
热议问题