0

When I want to make sure that an image / bitmap is really gone, I need to call

MyBitmap.Dispose()
MyBitmap = Nothing

Why is the call to .Dispose() necessary?

Why can't I simply say

MyBitmap = Nothing

?

I'm not good at C++, but I suspect that the underlying image / bitmap class knows when it's about to die, so why doesn't it call .Dispose on its own and lets the user take care of that?

tmighty
  • 10,734
  • 21
  • 104
  • 218
  • 2
    *I suspect that the underlying image / bitmap class knows when it's about to die* Your suspicion is wrong. The garbage collector will call the finalizer on the bitmap class at some non-deterministic point in the future, so to deterministically release resources the call to `Dispose` is necessary. – ta.speot.is Aug 20 '18 at 07:58
  • 3
    [Don't set the object to Nothing](https://stackoverflow.com/q/2785/4934172), it's not necessary _and not recommended_. Calling `Dispose()` is what's necessary. Check this post for more info: [Does the .dispose() method do anything at all?](https://stackoverflow.com/q/2024021/4934172) – 41686d6564 stands w. Palestine Aug 20 '18 at 08:19
  • @ta.speot.is I mean when I set the object to nothing. That destroys the object and doesn't let the GC do it, right? – tmighty Aug 20 '18 at 09:43
  • 3
    No it doesn't. It merely removes that variable's reference to the object. The object will continue to live until the GC runs and collects it (which will only happen if there are no more references to it). – Visual Vincent Aug 20 '18 at 09:54
  • 2
    As far as I know, `Dispose` exists _exactly_ for objects that the garbage controller can't clean up automatically... – Nyerguds Aug 20 '18 at 11:36
  • 1
    @VisualVincent Thank you so much, you're a great teacher. I think anybody would profit from your comment as an answer to my question. I have never seen this explained so well. – tmighty Aug 20 '18 at 14:25
  • 2
    I'd recommend reading Eric Lippert's treatise on the hazards of finalizers: https://ericlippert.com/2015/05/18/when-everything-you-know-is-wrong-part-one/ The many issues with finalizers are the main reason for using the `Dispose` pattern to reclaim any resources that aren't managed objects. In fact, the object *can* call `Dispose` on its own (the finalizer typically will include such a call), but for the various reasons Eric discusses, it's better to manage the lifetime of non-managed resources explicitly when you can. – Craig Aug 20 '18 at 16:27
  • Glad I can help! Though a complete answer would have to include what Nyerguds and Craig mentioned (which I do know about, though not enough to write an adequate answer :). The GC does automatically collect the _managed object_, however as the others said you want to call `Dispose()` to dispose of any unmanaged memory lying around (assuming the object has properly implemented cleanup). – Visual Vincent Aug 20 '18 at 22:15

0 Answers0