Search code examples
vb.netdispose

Why dispose an object when exiting an application?


Why do we dispose objects when we exit an application? In theory, wouldn't it be disposed of anyway when we close the program?

If not, how much could it impact the performance, that is, the amount of RAM it uses when running, if not disposed of?


Solution

  • If you take the IDisposable contract seriously then, no, disposing anything just before the program terminates makes no sense. As part of the shutdown procedure, the CLR runs the finalizers of any remaining objects. So the cleanup happens anyway, calling Dispose() does not make it any quicker and has no effect at all on resource usage.

    A word of caution is appropriate however. The contract does not always get used the way it was intended. It is very common to have to do some cleanup after using an object and very easy to forget to do so. The Using statement in particular is very attractive to make that semi-automatic. You can see me abuse the heck out of it in this answer. I went for it because it was convenient and impossible to not notice that you forgot to dispose. A pretty innocent fib. But it is not always that innocent. Something like using Dispose() to unsubscribe events is a pretty common crime for example. Not innocent, that's a leak when the client programmer doesn't dispose. Albeit that it still isn't a bug when it is skipped at program shutdown. But it could well be worse, like deleting a file or sending a "goodbye" message to another machine.

    So the rough guidance is that you'll never have to be sorry for disposing anyway and it is a good habit to get into. Particularly so if it is somebody else's code. But much less so if it is .NET Framework class, I can't think of a concrete case right now where it abuses the contract.