C# – Why call Dispose()? Memory leak won’t occur

cidisposablememory-leaksmemory-management

Edit: My question isn't getting the main answer that I was looking for. I wasn't clear. I would really like to know two things:

  1. Can NOT calling Dispose() cause memory leaks?
  2. What's the worst thing that can happen if you have a large program and never call Dispose() on any of your IDisposable objects?

I was under the impression that memory leaks could occur if Dispose() isn't called on IDisposable objects.

Per the discussion on this thread, my perception was incorrect; a memory leak will NOT occur if Dispose() isn't called.

Why ever bother calling Dispose() then? Is it just to free the resource immediately, instead of sometime later? What's the worst thing that can happen if you have a large program and never call Dispose() on any of your IDisposable objects?

Best Answer

Dispose is used to release non-managed resources. This could mean memory, if a class allocated non-managed memory, but it is more often native objects and resources like open files and database connections.

You often need to call Dispose on a class that itself doesn't have any non-managed resources, but it does contain another class that is disposable and may have non-managed resources.

It's also sometimes useful for developers to implement dispose to ensure deterministic finalization--guaranteeing the order in which resources are freed.

Also note that classes that implement dispose often also have a finalizer to release resourcdes if Dispose is not called. Objects with a finalizer have a different life-cycle than classes without one. When they are ready for GC, the GC will see that they have a finalizer and instead of immediately collecting the object when the GC is ready to, it puts it into the finalization queue. This means that the object lives for one extra GC iteration. When you call dispose, the implementation usually (but is not required to) calls GC.SuppressFinalize() which means the finalizer no longer needs to be called.

If a class implements IDisposable, you should always call Dispose().

Related Topic