gpt4 book ai didi

c# - .Net : Does my connection get closed via Dispose in this example?

转载 作者:太空狗 更新时间:2023-10-29 22:08:26 26 4
gpt4 key购买 nike

这是我的示例的简化版本:

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

当命令被释放时,连接是否关闭?或者我是否需要先使用 using 语句用于连接,然后在闭包中创建命令?

最佳答案

如果想让读者关闭连接,可以使用ExecuteReader()的重载:

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

默认情况下,处置阅读器不会释放连接。 - see MSDN for more info...

为了解决 Close()Dispose() 的问题,MSDN 指出:

If the DbConnection goes out of scope, it is not closed. Therefore, you must explicitly close the connection by calling Close or Dispose, which are functionally equivalent.

因此不一定需要设置自闭连接。主要区别在于可以重新打开已关闭的连接,但不能重新打开已处置的连接。 Dispose() 所做的主要额外工作是将内部设置为 null,这不会产生太大影响,因为无论如何连接都会超出范围。

关于c# - .Net : Does my connection get closed via Dispose in this example?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8620188/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com