根据我在这里关于Disposable对象的另一个问题,我们应该在using块结束之前调用Close()吗?
using (SqlConnection connection = new SqlConnection())
using (SqlCommand command = new SqlCommand())
{
command.CommandText = "INSERT INTO YourMom (Amount) VALUES (1)";
command.CommandType = System.Data.CommandType.Text;
connection.Open();
command.ExecuteNonQuery();
// Is this call necessary?
connection.Close();
}
Run Code Online (Sandbox Code Playgroud) 除了旧的已知事实,即connection.Close()vs connection.Dispose()是相同的 - 除了在关闭的连接上运行时,Close()在已处理的连接上运行引发异常Close()- 是的 - 我还有一个问题:
假设连接池已打开,(默认) - 为什么记住连接状态很重要?
我在这里读到了这个问题,它表明 - 避免打开和关闭连接可以节省性能.
这似乎是逻辑,但问题是连接永远不会被关闭!它只标记为关闭.
即使我在using范围内使用它- dispose只是关闭连接并将其放回池中.
即使我想要,我也不能让它开放(因为我希望其他人使用它).所以我不得不关闭/处理它.
看看Dapper 也实现了这种行为:
public static async Task<IEnumerable<T>> QueryAsync<T>(this...)
{
//...
bool wasClosed = cnn.State == ConnectionState.Closed;
using (var cmd = (DbCommand)command.SetupCommand(cnn, info.ParamReader))
{
try
{
if (wasClosed) await ((DbConnection)cnn).OpenAsync()...
//...
}
finally
{
if (wasClosed) cnn.Close();
}
}
}
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,"记忆"在这里实现.
NB,我已经问马克有关相关主题是-为什么短小精悍的样品中,他同时使用 …