簡體   English   中英

在使用塊或使用塊聲明時聲明IDisposable成員的區別?

[英]Difference in declaring IDisposable member in using block or at using block declaration?

我有以下代碼:

    using (SqlCommand command = new SqlCommand())
    {

        command.CommandType = System.Data.CommandType.StoredProcedure;
        command.Connection = new SqlConnection();
        command.CommandText = "";

        command.Parameters.Add(new SqlParameter("@ExperienceLevel", 3).Direction = System.Data.ParameterDirection.Input);

        SqlDataReader dataReader = command.ExecuteReader();
   }

在聲明SqlConnection的地方是否有任何功能影響我目前正在聲明它而不是這樣?:

using (SqlCommand command = new SqlCommand())
using (SqlConnection connection = new SqlConnection())

謝謝

是的,有區別。 處置SqlCommand不會自動處理與之關聯的SqlConnection 您可以通過這種方式泄漏連接,它會干擾ADO.NET連接池; 如果您在此代碼運行時查看數據庫服務器的活動,您將看到打開但未關閉的新連接。

您應該始終使用第二個版本。 實際上, SqlConnection對象是您真正需要 Dispose 你應該盡快處置任何實現IDisposable 東西 ,但是沒有配置SqlConnection是特別危險的。

是的,最好使用2個塊,每個資源1個。

在這種情況下,您可以只使用1但它應該在Connection周圍,而不是在Command周圍。

但你真的不想知道或關心這些細節。 如果一個類實現了IDispsoable接口,那么在using() { }塊中使用它的實例,除非有特殊原因不這樣做。

我使用以下模式:

using(var connection = new SqlConnection("ConnectionName"))
using(var command = new SqlCommand())
{
   command.Connection = connection;
   // setup command
   var reader = command.ExecuteReader();
   // read from the reader
   reader.Close();
}

是的,下面的代碼將正確配置SqlConnection,上面的代碼不會。 using塊(在內部實現為try ... finally )確保無論您如何退出塊,都將處置對象。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM