In code, say we have:
using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["LocalSqlServer"].ToString()))
{
cn.Open();
// Set all previous settings to inactive
using (SqlCommand cmd = new SqlCommand("UPDATE tblSiteSettings SET isActive = 0", cn))
{
cmd.ExecuteNonQuery();
}
cn.Close();
}
The cn.close is not technically required as garbage collection will take care of the connection for us.
However, I always like to close it anyway and to not rely on garbage collection. Is this bad? A waste of time? Or considered good practise to not rely on automation?
Thanks for your thoughts and opinions in advance. I’ll mark this as community wiki as it’s probably subjective.
You should never rely on the GC for this. Raymond Chen’s blog article about this is a good starting point. Essentially, if you don’t manually
Close/Disposeof your connection, then there is no guarantee that it will happen, because otherwise it would only ever happen whenDisposewas called from theFinalizerwhich might not ever happen:Yes, in practice, the finalizer for your connection will probably eventually happen, but even then, you are holding onto a live connection for longer than you actually need to. This can create issues if the database only allows a limited number of live connections at any one time.
What you’re doing is considered good practice: when you’re done with resources, free them up. If an object is
IDisposable,Disposeof it when you can.