Do I need to call Dispose() on managed objects?

后端 未结 11 1846
忘了有多久
忘了有多久 2020-12-08 14:51

I can\'t believe I\'m still confused about this but, any way, lets finally nail it:

I have a class that overrides OnPaint to do some drawing. To speed things up, I c

11条回答
  •  自闭症患者
    2020-12-08 15:16

    There is a marked irony in your approach. By pre-creating the pens/brushes, you are exactly creating the problem that Dispose() is trying to solve. Those GDI objects will be around longer, just like they would be when you don't call Dispose(). It is actually worse, they'll be around at least until the form is closed.

    They are probably around long enough to get promoted to generation #2. The garbage collector doesn't do a gen#2 collection very often, it is now more important to call Dispose() on them. Do so by moving the Dispose() method of the form from the Designer.cs file to your form.cs file and add the Dispose calls.

    But, do this the Right Way. Pens and brushes are very cheap objects. Create them when you need them, in the Paint event. And use the using statement so they'll get disposed right away. Use the Stopwatch class to re-assure yourself this doesn't actually cause any slowdown.

提交回复
热议问题