views:

189

answers:

2

the question is why we need to call dispose() on some objects?
why doesnt the garbage collector collect the object when it goes out of scope?
i am trying to understand the reason why it was implemented like that.
i mean it would be easier if object when the garbage collector collected out of scope objects.
thanks

+6  A: 

Dispose is used to clean-up unmanaged resources (e.g. wrappers for database connections, old COM libraries, ...).

Edit: Some MSDN Links with further details:
http://msdn.microsoft.com/en-us/library/b1yfkh5e(VS.71).aspx
http://msdn.microsoft.com/en-us/library/0xy59wtx(VS.71).aspx

To specify what happens with unmanaged resources when the garbage collector reclaims an object, you have to override the protected Finalize() method: http://msdn.microsoft.com/en-us/library/system.object.finalize(VS.71).aspx

weichsel
+11  A: 

The garbage collector is non-deterministic - it collects objects at some point after they're no longer referenced, but it's not guaranteed to happen in a timely fashion. This has various benefits over reference counting, including allowing cyclic dependencies and the performance benefit of not incrementing and decrementing counters all over the place.

However, it does mean that for resources which should be cleaned up in a timely manner (such as database connections, file handles etc - almost anything other than memory) you still need to explicitly dispose of the resource. The using statement makes this pretty easy though.

Jon Skeet
well i had an application that was generating Bitmaps and i wasnt calling dispose() and the application started comsuming gigabytes of memory.altought i create a bitmap every 20 seconds and its Immediately saved to disk and goes out of scope.but the garbage collector didnt seem to work at all. because the memory was going only up.
Karim
@Karim: Well, you should certainly have been disposing of those Bitmaps. You'd have to look at what GCs were happening etc to diagnose why it wasn't collecting them eventually - but there's a reason why Image implements IDisposable...
Jon Skeet