SqlDataReader and concurrency/deallocation issues

泄露秘密 提交于 2019-12-11 18:49:27

问题


Running the below code is giving me an error:

.NET Framework execution was aborted by escalation policy because of out of memory. System.InvalidOperationException: There is already an open DataReader associated with this Command which must be closed first.

I have the following code all over the place to run my sql:

sql.Append(string.Format("SELECT TableId FROM ps_SavedTables WHERE guid = '{0}'", guid));

    using (IDataReader reader = SqlHelper.GetDataReader(sql.ToString())) {
        if (reader.Read()) {
            result = reader.IsDBNull(0) ? string.Empty : reader[0].ToString();
        }
        //CDW added to close SqlDataReader
        reader.Close();
    }

The GetDataReader is defined by this:

public static SqlDataReader GetDataReader(string sql, string connectionString) {
    lock (_lock) {
        SqlConnection connection = null;
        try {
            connection = GetConnection(connectionString);
            //connection.Open();
            using (SqlCommand cmd = new SqlCommand(sql, connection)) {
                WriteDebugInfo("GetDataReader", sql);
                return cmd.ExecuteReader(CommandBehavior.CloseConnection);
            }
        }
        catch (Exception e) {
            if (connection != null)
                connection.Dispose();
            throw new DataException(sql, connectionString, e);
        }

    }
}

回答1:


The lock needs to be at the reader level... Multiple threads are opening readers



来源:https://stackoverflow.com/questions/10712937/sqldatareader-and-concurrency-deallocation-issues

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!