I have written web application and while testing it I found that the connections established with the server are not being closed even though I close the connection in the application. Even after the web page is closed, the connection remains as it is.
Here is a sample code snippet which opens a connection and closes it:
protected void OpenConnection_Click(object sender, EventArgs e)
{
SqlConnection conn = null;
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
builder.DataSource = "MyServerName";
builder.InitialCatalog = "Northwnd";
builder.IntegratedSecurity = true;
builder.ApplicationName = "My Test ASP";
try
{
conn = new SqlConnection(builder.ConnectionString);
conn.Open();
conn.Close();
}
catch (SqlException ex)
{
ex.Message.ToString();
}
}
In the activity monitor the connection still remains. If I execute the same code in a normal Windows application the connection is getting closed properly.
Please help me how to resolve this issue.
You should use
usingfor better managing resources. There is a big flaw in your code that if your code encounters an exception, the connection will not be closed and this will cause severe problems. Rewriting your code would result in:When the using block ends, it automatically calls the dispose method of the using variable which is SqlConnection here. Note that calling dispose on SqlConnection will also call its Close() method, you can investigate it in reflector.