2011-05-19 100 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()調用可能永遠不會運行。

相關問題