简体   繁体   English

导致 memory 泄漏的通用数据读取器

[英]Generic Data Reader causing memory leak

I created a generic method in reading sql statement, but I am having a memory leak whenever I do a select query and using while read.我创建了一个通用方法来读取 sql 语句,但是每当我执行 select 查询并在读取时使用时,我都会出现 memory 泄漏。

Sample Query:示例查询:

    public CMItemPackagingType GetItemPackagingType(int itemID)
    {  
        try
        {               
            List<CommandParameter> param = new List<CommandParameter>();
            StringBuilder sb = new StringBuilder();
            using (BaseConnection db = new BaseConnection())
            {
                sb.Append("SELECT RATIO, PACKAGING_TYPE_CODE FROM ITEM_PACKAGING_TYPE WHERE ROUND_UP = 0.01 AND ITEM_ID = @itemID");

                param.Add(new CommandParameter("@itemID", itemID));
                using (var rs = db.ExecSQL(sb.ToString(), param.ToArray()))
                {
                    CMItemPackagingType cmItemInfo = new CMItemPackagingType();

                    while (rs.Read())
                    {
                        CMItemPackagingType list = new CMItemPackagingType();
                        if (!rs.IsDBNull(0))
                            list.Ratio = Convert.ToInt32(rs.GetValue(0));
                        if (!rs.IsDBNull(1))
                            list.PackagingTypeCode = rs.GetValue(1).ToString();

                        cmItemInfo.ItemPackagingTypeList.Add(list);
                    }
                    return cmItemInfo;
                }        
            }       
        }
        catch (Exception ex)
        {                
            GlobalFramework.HandleException(ex);
        }
        return null;
    }       

Generic Reader:通用阅读器:

public DbDataReader ExecSQL(string sqlStmt, CommandParameter[] param)
    {

            List<MySqlParameter> p = ParameterMySql(param);
            _mySqlConn = new MySqlConnection(szConnect);
            if (_mySqlConn.State == ConnectionState.Open)
            {
                _mySqlConn.Close();
            }
            _mySqlConn.Open();
            _mySqlComm = new MySqlCommand(sqlStmt, _mySqlConn);
            _mySqlComm.Parameters.AddRange(p.ToArray());
            MySqlDataReader reader = _mySqlComm.ExecuteReader();

            return reader;

    }

I'm assuming the BaseConnection is a wrapper around a SqlConnection and _mySqlConn is an instance of BaseConnection.我假设 BaseConnection 是 SqlConnection 的包装器,而 _mySqlConn 是 BaseConnection 的实例。 I suspect the issue is that you are opening and closing the connection in ExecSQL and at the same time have a using statement around BaseConnection creating this leak.我怀疑问题是您在 ExecSQL 中打开和关闭连接,同时有一个围绕 BaseConnection 的 using 语句创建了这个泄漏。 I would refactor your code with proper placement of using statements to ensure correct disposal of the objects and freeing of resources.我会通过正确放置 using 语句来重构您的代码,以确保正确处理对象并释放资源。

Example例子

        var query = "YOUR QUERY";

        using (var connection = new SqlConnection("YOUR CONNECTION STRING"))
        {
            using (var command = new SqlCommand(query, connection))
            {
                await connection.OpenAsync();

                using (var reader = await command.ExecuteReaderAsync())
                {
                    if (reader != null)
                    {
                        while (await reader.ReadAsync())
                        {
                            // your logic
                        }
                    }
                } // reader closed and disposed up here
            } // command disposed here
        } //connection closed and disposed here
    }

Also notice how I'm using the async versions of the ADO.NET methods.另请注意我如何使用 ADO.NET 方法的异步版本。 Async commands are critical in achieving scale, throughput, and latency.异步命令对于实现规模、吞吐量和延迟至关重要。

I recommend you use Dapper over trying to develop a generic data reader and writing all the boilerplate ADO.NET code yourself.我建议您使用Dapper ,而不是尝试开发通用数据读取器并自己编写所有样板 ADO.NET 代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM