我的假设是,如果 Sqlconnection 在 Using 语句中打开 With,dispose 事件将在语句执行后自动发生,如果我在 Using 语句中强制关闭连接,将会发生什么糟糕的事情练习 ?
using (SqlConnection conn = new SqlConnection(ConfigurationSettings.AppSettings["Constring"]))
{
// SqlConnection conn = new SqlConnection(ConfigurationSettings.AppSettings["Constring"]);
conn.Open();
String query = String.Empty;
query = "exec " + StoredProcedure + " " + sampleproc + "";
using (SqlDataAdapter mainTableAdapter = new SqlDataAdapter(query, conn))
{
System.Data.DataSet mainTableDS = new System.Data.DataSet();
mainTableAdapter.Fill(mainTableDS);
conn.Close();
mainTableAdapter.Dispose();
conn.Dispose();
return mainTableDS;
}
}
最佳答案
无需同时调用
Close()
和Dispose()
;调用Dispose()
将自动关闭连接并释放对象。无需在
using
block 内调用Close()
或Dispose()
。using
语句自动处理对象(并且由于上面的 #1 也关闭了连接)。
此外,关于上面的#2 的注释。如果 Microsoft 的 guidance is followed 多次调用 Dispose()
应该是安全的应该 :
If an object's Dispose method is called more than once, the object must ignore all calls after the first one. The object must not throw an exception if its Dispose method is called multiple times. Instance methods other than Dispose can throw an ObjectDisposedException when resources are already disposed.
关于c# - 如果在 C# 中的 Using 语句中调用连接关闭事件会发生什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30388062/