How can I avoid connection leak? thanks!

D

davidw

I have code like this

try{
sqlConn = new SqlConnection(gDSN);
sqlConn.Open();
.....
....
catch(Exception e) {
ShowError("...", e);
}
finally {
if(sqlConn!=null)
{
sqlConn.Close();
sqlConn.Dispose();
}
}

But it seems the connection can not be released, and it accumulates to 100
and then no more connection unless I restart the project. Any idea?
 
A

Allen Anderson

the 'using' statement is what your looking for. It will close out a
reference when it goes out of scope. hence,

using ( sqlConn = new SqlConnection( gDSN ) )
{
sqlconn.Open();
...
}

this will take care of closing the connection also.


Allen Anderson
http://www.glacialcomponents.com
mailto: allen@put my website url here.com
 
M

Miha Markic [MVP C#]

Hi david,

I am guessing that it happens because connections are pooled (by default it
will cache one connection).
If you create and dispose another connection, does in increase again?
 
D

davidw

The piece of code is part of a web application, I did a test, It can be
called 100 times before it waits for connection, so it is the pooling, when
it reachs the default size, it will wait for free connection. I think the
code worked for me. But not sure why it is not now. And that only happens
when I run the web application under VS.


Miha Markic said:
Hi david,

I am guessing that it happens because connections are pooled (by default it
will cache one connection).
If you create and dispose another connection, does in increase again?

--
Miha Markic [MVP C#] - RightHand .NET consulting & development
miha at rthand com
www.rthand.com

davidw said:
I have code like this

try{
sqlConn = new SqlConnection(gDSN);
sqlConn.Open();
....
...
catch(Exception e) {
ShowError("...", e);
}
finally {
if(sqlConn!=null)
{
sqlConn.Close();
sqlConn.Dispose();
}
}

But it seems the connection can not be released, and it accumulates to 100
and then no more connection unless I restart the project. Any idea?
 
P

Peter Lin

It's not necessary to call sqlConn.close() and sqlConn.dispose()
Dispose will implicitly call close method.
When you use using(.. )
the object you use need to implement IDispose,
That means ,after go out of scope, it will call dispose method for you
and internally it will call close method..
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top