Avoid using “using()”

The using statement in C#, seems to be quite useful especially to a developer as theoretically, you not have to do anything to release any memory you might have used and the CLR automatically frees up this memory for you.

However, over time, I have had so many issues with it and subtle problems (in certain situations) I am starting to avoid it now.

The two best examples that I can think of are database connection pools and WCF connections. You might think that a “using” statement would close the connection and free up the resources when the scope finishes – but it does not. If you are thinking that a “Close()” is called for you automatically, you might be surprised to know that it is not.

For example if you are using a connection pool, over time you will get timeout errors (which are quite difficult to track down if you got some intelligent tool creating your DALs for you). This of course is because the connections are not closed and overtime you end up exhausting your pool. To avoid this you should explicitly call a “close()” method.

Similar story with WCF. If you find that after a few calls (or over some longer period of time), if you start seeing some degradation in performance and your response times taking a long time, then you need to explicitly close the connection as the using statement will not do it for you.

Also, if you are testing your WCF service on XP/Vista you might hit the built-in limit that limits the number of concurrent connections that XP/Vista allow.

Lastly, if you are using WCF, if possible then upgrade to .NET 3.5 as there are a lot of benefits which can get out of the box.

Published by

Amit Bahree

This blog is my personal blog and while it does reflect my experiences in my professional life, this is just my thoughts. Most of the entries are technical though sometimes they can vary from the wacky to even political – however that is quite rare. Quite often, I have been asked what’s up with the “gibberish” and the funny title of the blog? Some people even going the extra step to say that, this is a virus that infected their system (ahem) well. [:D] It actually is quite simple, and if you have still not figured out then check out this link – whats in a name?

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.