Search code examples
c#asp.netdisposesqlconnection

Should I Dispose() a SqlConnection if I don't open() it?


We are having occasional SqlServer lock-ups requiring a restart and I'm reviewing legacy code to try and isolate causes.

In a Library file that is included in every c# ASP.Net page I find this:

sConString  = ConfigurationSettings.AppSettings.Get("SQLConnString"); 
oCon = new SqlConnection(sConString);

If a page does database access it starts with

oCon.Open();

and ends with:

oCon.Close();   
oCon.Dispose();

But some pages dont do database access so there is no Dispose(); called.

My question is, is there an overhead caused by creating a SqlConnection that doesnt get Disposed()?

Thanks for any suggestions


Solution

  • Dispose() has more to do with memory management than connection management. I don't think this will solve your issue. You might want to make sure you close your connection in the finally block of a Try-Catch. This way the connection will be closed if your open connection is successful or not.