c# - IDbCommand 是否从实现 IDisposable 的类中被释放?

标签 c# database idisposable

我有一个数据访问类的基类。此类实现 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/

相关文章:

c# - 关于Entity Framework Context Lifetime的问题

c# - X509CertificateValidationMode 在 Linux 中不起作用?

c# - 具有不同数量对象的 WPF MVVM View 。如何?

c# - 'Access-Control-Allow-Origin' header 包含多个值。但是我在标题中只定义了一个值?

c# - Linq Any() 抛出错误 : String was not recognized as a valid boolean

database - Oracle:使用动态查询更新多列

c# - 如果我在 using 语句结束之前返回会怎样?会调用 dispose 吗?

database - 从 Access 事件驱动数据宏调用 C# 代码?

database - 使用 Erlang/OTP 的面向服务的架构 : how to use messaging properly

c# - ClientBase 没有实现 IDisposable 成员