gpt4 book ai didi

c# - 如果您已经关闭 SqlConnection,是否需要关闭/处置 SqlDataReader?

转载 作者:太空狗 更新时间:2023-10-29 23:56:17 24 4
gpt4 key购买 nike

我注意到了 This question ,但我的问题更具体一些。

使用有什么好处

using (SqlConnection conn = new SqlConnection(conStr))
{
using (SqlCommand command = new SqlCommand())
{
// dostuff
}
}

代替

using (SqlConnection conn = new SqlConnection(conStr))
{
SqlCommand command = new SqlCommand();
// dostuff
}

显然,如果您计划使用同一连接运行多个命令,这确实很重要,因为关闭 SqlDataReader 比关闭并重新打开连接(调用 conn.Close( );conn.Open(); 也将释放连接。

我看到很多人坚持认为未能关闭 SqlDataReader 意味着留下打开的连接资源,但这不是只有在您不关闭连接时才适用吗?

最佳答案

在我看来,这里有两条规则要遵循:

  1. 实现 IDisposable 的类应该包装在 using block 中。
  2. 您不应依赖类的 IDisposable 实现来忽略规则 1。

也就是说,即使您知道处理连接对象会处理与其关联的命令对象,您也不应依赖此行为。

顺便说一下,可以用更简洁的方式嵌套使用 block :

using (SqlConnection conn = new SqlConnection(conStr))
using (SqlCommand command = new SqlCommand())
{
// dostuff
}

我会用

SqlCommand command = conn.CreateCommand();

而不是创建一个新的 SqlCommand,然后将其与连接相关联。

关于c# - 如果您已经关闭 SqlConnection,是否需要关闭/处置 SqlDataReader?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2655978/

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