2011-05-19 99 views
0

我编写了web应用程序,并在测试它时发现即使关闭应用程序中的连接,与服务器建立的连接也没有关闭。即使在网页关闭后,连接仍然保持原样。 这里是一个打开一个连接,并关闭它的样本代码段:SQL Server连接没有在ASP.net web应用程序中关闭

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(); 
    } 

} 

在活动监控连接仍然存在。如果我在正常的Windows应用程序中执行相同的代码,连接就会正常关闭。

请帮我解决这个问题。

+0

即使在使用(SqlConnection conn = new SqlConnection(builder.ConnectionString)){..........}之后,服务器中的连接未关闭。 – Nagesh 2011-05-19 05:44:36

回答

2

您应该使用using来更好地管理资源。代码中存在一个很大的缺陷,即如果您的代码遇到异常,连接将不会关闭,这将导致严重问题。重写你的代码将导致:

protected void OpenConnection_Click(object sender, EventArgs e) 
{ 
    SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(); 
    builder.DataSource = "MyServerName"; 
    builder.InitialCatalog = "Northwnd"; 
    builder.IntegratedSecurity = true; 
    builder.ApplicationName = "My Test ASP"; 

    using (SqlConnection conn = new SqlConnection(builder.ConnectionString)) 
    { 
    try 
    { 
     conn.Open(); 
     // Do Some stuff with SqlConnection 
    } 
    catch (SqlException ex) 
    { 
     ex.Message.ToString(); 
    } 
    } 
} 

当using块结束时,它会自动调用使用变量SqlConnection的dispose方法。请注意,在SqlConnection上调用dispose也会调用它的Close()方法,您可以在反射器中调查它。

0

尝试投入使用,像这样的连接:

protected void OpenConnection_Click(object sender, EventArgs e) 
{ 
    SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(); 
    builder.DataSource = "MyServerName"; 
    builder.InitialCatalog = "Northwnd"; 
    builder.IntegratedSecurity = true; 
    builder.ApplicationName = "My Test ASP"; 

    using(var conn = new SqlConnection(builder.ConnectionString)) 
    { 
     try 
     { 
      conn.Open(); 
     } 
     catch (SqlException ex) 
     { 
      ex.Message.ToString(); 
     } 
    } 
} 

自动使用部署为你的连接。

0

试试这个

using (SqlConnection conn = new SqlConnection(builder.ConnectionString) 
    { 
     conn.Open(); 
     conn.Close(); 
     conn.Dispose(); 
    } 
0

我觉得con.Dispose丢失。

替代

using语句SQL连接实例

using(sqlconnection con = new sqlconnection()) 
{ 
    Your logic 
} 

通过这种连接将自动获得处置。

0

确认没有异常被抛出,否则conn.Close()调用可能永远不会运行。

相关问题