2011-12-23 42 views
5

這裏是我的實例的簡化版本:.Net:在此示例中,我的連接是否通過Dispose關閉?

using (DbCommand cmd = new SqlCommand("myProcedure", (SqlConnection)DataAccessHelper.CreateDatabase().CreateConnection()) { CommandType = CommandType.StoredProcedure }) 
{ 
    cmd.Connection.Open(); 
    using(IDataReader dr = cmd.ExecuteReader()) 
     doWork(dr); 
} 

當命令被設置,在連接關閉?或者我需要將第一個使用語句作爲連接,然後在關閉中創建命令?

回答

11

如果你想閱讀器關閉連接,你可以使用的ExecuteReader()的過載:

... 
using (IDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection)) 
... 

默認情況下,設置一讀者不釋放連接。 - see MSDN for more info...

爲了解決Close()問題VS Dispose(),在MSDN指出:

如果的DbConnection超出範圍,它不會被關閉。因此,您必須通過調用Close或Dispose, 明確地關閉連接,這些功能是等效的。

因此,自閉合連接不一定需要設置。主要區別在於可以重新打開關閉的連接,但處理後的連接不能。 Dispose()所做的主要額外工作是將內部設置爲null,由於連接超出範圍,因此不會產生太大影響。

+0

我不相信配置連接,只是關閉它。 – 2011-12-23 20:24:03

+0

這會處理連接嗎? – 2011-12-23 20:25:52

+0

從MSDN,在連接上調用Close()和Dispose()在功能上是等效的: – 2011-12-23 20:38:53

4

詹姆斯邁克爾黑爾的作品,但你也想要處理你的連接。試試這個:

using (SqlConnection conn = (SqlConnection)DataAccessHelper.CreateDatabase().CreateConnection()) 
using (DbCommand cmd = new SqlCommand("myProcedure", conn) { CommandType = CommandType.StoredProcedure }) 
{ 
    cmd.Connection.Open(); 
    using(IDataReader dr = cmd.ExecuteReader()) 
     doWork(dr); 
} 
3

您應該使用

using(var connection = (SqlConnection)DataAccessHelper.CreateDatabase().CreateConnection()) 
{ 
connection.Open(); 
.... 
} 

因爲即使你關閉連接,你仍然需要處理它。請注意,SQLConnection確實在Dispose中調用了Close。問題是,如果你必須自己撥打Close,你必須把它放到try...catch,這樣才能保證你的內存不會泄漏。框架中還有其他類型的Close不在Dispose中,在我看來應該被包裝。

+0

我的答案中顯示的兩行「使用」在這種情況下效果很好。 – 2011-12-23 20:28:25

+0

@MikeC。是的,我只是想討論不同的Dispose實現。 – 2011-12-23 20:34:42

相關問題