Groups | Blog | Home
all groups > dotnet ado.net > august 2004 >

dotnet ado.net : Database Connection not releasing following .Close


goosh NO[at]SPAM yahoo.com
8/31/2004 6:12:54 PM
Hi There.

I have a complicated application that I'm seeing issues with where my
various connections to my sql server are not getting released. Rather
then delve into that, I created the following very simple asp.net
application that executes the following code:

private void Button1_Click(object sender, System.EventArgs e)
{
// Build connection
SqlConnection connection = new SqlConnection();
string sConnection = "data source=localhost;" +
"initial catalog=northwind;" +
"User ID=webuser;" +
"Password=;";
connection.ConnectionString = sConnection;
connection.Open();

// Build Query
SqlCommand objCmd = new SqlCommand();
objCmd.Connection = connection;
objCmd.CommandText = "select * from categories";

try
{
objCmd.ExecuteNonQuery();
}
catch (Exception ex)
{
string test = ex.Message;
}
finally
{
connection.Close();
connection = null;
objCmd = null;
}

}

Upon execution (in debug mode) of the above .aspx page I am able to
see the connection still alive via a sp_who query within my sql
database. In addition, when I stop debugging the connection still
remains.

From everywhere I've read (including MS), the above code is
appropriate. However, the fact that the connection remains is very
concerning. However, each time I restart my application it appears
that no new connections are created, almost as though it's reusing my
old connection. Therefore, I'm wondering if this is the typical
behavior as without knowing any better I would expect the connection
to be destroyed/recreated on each application instance.

Thanks in advance,
Miha Markic [MVP C#]
9/1/2004 7:05:15 AM
Hi,

This is by design and it is called connection pooling.
See:
Connection Pooling for the .NET Framework Data Provider for SQL Server
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/cpconconnectionpoolingforsqlservernetdataprovider.asp

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

[quoted text, click to view]

Joyjit Mukherjee
9/1/2004 10:36:40 AM
Hi,

the connection is maintained in a pool so that subsequent requests to use it
may get served from the pool rather than creating it altogether. Best
practises for using ADO .NET objects says that you should release / destroy
objects after you are finished with it to let the CLR garbage collect it.

Regards
Joyjit

[quoted text, click to view]

AddThis Social Bookmark Button