我有一个数据访问类的基类。此类实现 IDisposable。该基类包含 IDbConnection 并在构造函数中对其进行实例化。
public class DALBase : IDisposable
{
protected IDbConnection cn;
public DALBase()
{
cn = new MySqlConnection(connString);
}
public void Dispose()
{
if (cn != null)
{
if (cn.State != ConnectionState.Closed)
{
try
{
cn.Close();
}
catch
{
}
}
cn.Dispose();
}
}
}
继承自此类的类实际访问数据库:
public class FooDAL : DALBase
{
public int CreateFoo()
{
// Notice that the cmd here is not wrapped in a using or try-finally.
IDbCommand cmd = CreateCommand("create foo with sql", cn);
Open();
int ident = int.Parse(cmd.ExecuteScalar().ToString());
Close();
cmd.Dispose();
return ident;
}
}
使用 FooDAL 的类使用 using 模式来确保使用如下代码在 FooDAL 上调用 Dispose:
using(FooDAL dal = new FooDAL())
{
return dal.CreateFoo();
}
我的问题是,即使 IDbCommand 没有包装在 using 模式或 try-finally 中,这是否也能确保正确处理它?如果在命令执行过程中出现异常怎么办?
此外,出于性能原因,在 CreateFoo 中而不是在基类的构造函数中实例化连接会更好吗?
感谢任何帮助。
最佳答案
鉴于连接已合并,只需在 CreateFOO 方法(使用 using block )中创建 MySqlConnection。
不要为关闭它而烦恼,因为它会在 using block 的末尾自动处理/关闭。
public int CreateFoo()
{
using (var cn = new MySqlConnection(connString))
{
// Notice that the cmd here is not wrapped in a using or try-finally.
using (IDbCommand cmd = CreateCommand("create foo with sql", cn))
{
cn.Open();
return int.Parse(cmd.ExecuteScalar().ToString());
}
}
}
关于c# - IDbCommand 是否从实现 IDisposable 的类中被释放?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5031274/