SqlDataReader and concurrency/deallocation issues

2019-08-27 02:49发布

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条回答
对你真心纯属浪费
2楼-- · 2019-08-27 03:20

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

查看更多
登录 后发表回答