Jan Schreuder on .Net

.Net code samples, experiences, observations

View my professional profile on LinkedIn

Recent Posts

Tags

News

  • Inappropriate comments will be deleted at my discretion.

    The information and code samples in this weblog is provided "AS IS" without warranty of any kind, either expressed or implied, including but not limited to the merchantability and/or fitness for a particular purpose.

Community

Email Notifications

Tool suppliers

Tools

General

Microsoft

Favorite blogs

Archives

Dispose and the Garbage collector

I was assigned to a .Net web project some years ago to see why the application continued to allocate more and more memory untill IIS thought it was to time to restart the application. I solved a lot of the problems in that project simply by calling the Dispose method on any object that implemented one, once I didn't need that object anymore. Since then, I've tried to make it a rule to call the dispose method for all objects that expose that method.

But I still see projects where this doesn't happen. When I discus this with the developers on that project, they are under the impression that it is not necessary to do this. People think that the Garbage collector will clean up resources. Well, it might but you never know when! I believe it is good practice to call the Dispose method on any object that exposes it once you no longer need that object. The Dispose method will clean up any resources that need to be cleaned up. For example, the SqlConnection object will clean up anything related to the connection, especially the unmanaged resources that the GC will never touch!

I found some interesting reading on the subject of Dispose, Finalize and the garbage collector!

Comments

Joshua Langemann said:

The C# (and now VB) "using" statement is really helpful to ensure that you properly dispose of objects. I don't know how many times I missed disposing of things like DataReaders prior to learning about using. Try/Finally blocks (without the Catch) are also handy, since they guarantee that the Finally block will run even when you have no need to catch exceptions.
# January 26, 2006 1:29 PM
Leave a Comment

(required) 

(required) 

(optional)

(required)