Click here to Skip to main content
15,881,803 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Why its highly recommended to dispose all objects/Datasets/Datatables in finally block when .net have its own Garbage collector which handles memory deallocation automatically and runs after specific interval.

Thanks in advance.
Posted
Updated 22-Mar-13 1:19am
v2
Comments
ZurdoDev 22-Mar-13 7:22am    
Because it is my understanding that there is no specific interval. In one of the versions of .Net, which may have been fixed now, there was also an issue with how the garbage collector was counting the pointer to an object and in some cases it was wrong.

As practice, it's just a good idea to clean up after yourself.

There are a couple of reasons.
The first one is because some objects use resources other than memory, which it is important to return to the system as soon as possible so that they can be reused for other purposes. Some of these may be local to you application, others may be local to your whole PC. If they are not released, then "leaks" occur because the total number of available resources drops each time you create an instance, and sooner or later the system runs out. Since the Garbage Collector is only activated by low memory, there is no mechanism for returning these resources other than explicit Disposal. Such objects include (but are not limited to) Graphics contexts, Pens and SqlConnection / SqlCommand objects.

It also helps to free up files which are held open by some commands: Bitmap.FromFile for example aquires a write lock on the file which is only released when the bitmap is disposed. Since you can't rrely on teh GC kicking in at any point, Disposing of the bitmap is the only way to free up the file it is based on for writing.

It also helps because it can keep the memory footprint down - if you constantly allocate and Dispose objects of the same size, the same memory can be re-used and your whole app runs more smoothly because the GC is never needed (and it always runs at the most awkward times :laugh: )
 
Share this answer
 
Comments
José Amílcar Casimiro 22-Mar-13 7:40am    
Good response. +5
frostcox 22-Mar-13 8:04am    
Great Explination. +5
deepakdynamite 22-Mar-13 10:07am    
Thanks alot for such a wonderful justification
OriginalGriff 22-Mar-13 10:32am    
You're welcome!
You should dispose objects explicitly when they use unmanaged code inside them.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900