ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

c# – IDbCommand是否从实现IDisposable的类中处理掉?

2019-07-05 00:07:43  阅读:245  来源: 互联网

标签: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被正确处理掉,即使它没有包含在使用模式或try-finally中?如果在执行命令期间发生异常会发生什么?

另外,出于性能原因,在CreateFoo中而不是在基类的构造函数中实例化连接会更好吗?

任何帮助表示赞赏.

解决方法:

鉴于连接是池,只需在CreateFOO方法中创建MySqlConnection(使用using块).

不要打扰关闭它,因为它将在使用块的末端自动处理/关闭.

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,database,idisposable
来源: https://codeday.me/bug/20190704/1382098.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有