Disposing Resources

When you are working with managed resources in C#. you can usually let the Garbage Collector deal with tidying up after you. Memory allocation problems that are familiar in the past with languages such as C are dealt with for you.

The Garbage Collector is not magic. First off you don’t usually control when garbage collection occurs. The Framework will initiate collection whenever it thinks it’s necessary. Sometimes you’ll go a long time between collections, but as resources begin to become scarce, it will happen more often.

You can call a forced collection, but it’s rare that this is  a good idea. The Garbage Collector itself will manage when collections need to occur. Forcing multiple early collections is almost always worse than letting the collection happen automatically.

The Garbage Collector cannot deal with unmanaged resources. The most common of these that you will encounter are related to database connections, and file access.

You should do two things when dealing with unmanaged resources. First off, wrap them in using statements. This ensures that the dispose method is called once you are finished with the resource.

The second thing to do is to make sure that your classes implement the IDisposable interface. This means that when the Dispose() method is called you have a chance to clean up your unmanaged resources, to prevent any memory leaks and ensure that the Garbage Collector can do it’s job.

There are a lot of further complexities to the Garbage Collection and memory management, most of the time you won’t have to worry too much about them, but it’s good to know the basics for the times you do.


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