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

后端 未结 11 1848
忘了有多久
忘了有多久 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:17

    It is not correct. You need to dispose objects that implement IDisposable. That is why they implement IDisposable - to specify the fact that they wrap (directly or indirectly) unmanaged resources.

    In this case, the unmanaged resource is a GDI handle, and if you fail to dispose them when you are actually done with them, you will leak those handles. Now these particular objects have finalizers that will cause the resources to be released when the GC kicks in, but you have no way of knowing when that will happen. It might be 10 seconds from now, it might be 10 days from now; if your application does not generate sufficient memory pressure to cause the GC to kick in and run the finalizers on those brushes/pens/fonts/etc., you can end up starving the OS of GDI resources before the GC ever realizes what's going on.

    Additionally, you have no guarantee that every unmanaged wrapper actually implements a finalizer. The .NET Framework itself is pretty consistent in the sense that classes implementing IDisposable implement it with the correct pattern, but it is completely possible for some other class to have a broken implementation that does not include a finalizer and therefore does not clean up properly unless Dispose is called explicitly on it. In general, the purpose of IDisposable is that you are not supposed to know or care about the specific implementation details; rather, if it's disposable, then you dispose of it, period.

    Moral of the story: Always dispose IDisposable objects. If your class "owns" objects that are IDisposable, then it should implement IDisposable itself.

提交回复
热议问题