Posted by: Cirilo Meggiolaro | 11/2/2008

Tip of the day #19 – Explicitly release resources.

It’s very usual to develop code that will work with files, database connections and other kind of objects that consume unmanaged resources.

If you are consuming third part objects or .NET native ones, you may check if the object implements the IDisposable interface. A quick look at the list of available methods will give you the answer. Even if you have not heard about the interface yet, you have probably seen the Dispose method somewhere.

It’s a convention that the Dispose method releases managed and unmanaged resources and the public Dispose method provides a way to explicitly release resources from your calling code.

So, today’s tip is very straightforward, easy to implement and it is matter of discipline to apply it.

How to…

The code snippet uses a DataSet named ds. The first step is to check if the object has not been disposed yet and then calls the Dispose method to explicitly release resources and finally let the Garbage Collector knows that the object is not necessary anymore.

if (ds != null)
{
ds.Dispose();
ds = null;
}

Keep your application healthy! If you use resources, release them.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Categories

%d bloggers like this: