SqlDataReader的和并发/释放问题 [英] SqlDataReader and concurrency/deallocation issues

查看:739
本文介绍了SqlDataReader的和并发/释放问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

运行低于code是给我的错误:

.NET框架的执行被中止升级策略,因为出来的内存。
System.InvalidOperationException:有已与此命令必须先关闭相关联的打开的DataReader

我有以下的code遍布运行我的SQL的地方:

  sql.Append(的String.Format(选择从TABLEID ps_SavedTables其中GUID ='{0}',GUID));    使用(IDataReader的读卡器= SqlHelper.GetDataReader(sql.ToString())){
        如果(reader.Read()){
            结果= reader.IsDBNull(0)?的String.Empty:阅读[0]的ToString();
        }
        // CDW加入到关闭SqlDataReader的
        reader.Close();
    }

该GetDataReader由该定义的:

 公共静态SqlDataReader的GetDataReader(SQL字符串,字符串的connectionString){
    锁(_lock){
        SqlConnection的连接= NULL;
        尝试{
            连接=的getConnection(的connectionString);
            //connection.Open();
            使用(CMD的SqlCommand =新的SqlCommand(SQL,连接)){
                WriteDebugInfo(GetDataReader,SQL);
                返回cmd.ExecuteReader(CommandBehavior.CloseConnection);
            }
        }
        赶上(例外五){
            如果(连接!= NULL)
                connection.Dispose();
            抛出新DataException(SQL,ConnectionString,则E);
        }    }
}


解决方案

锁必须在读者层面......多个线程,读者打开

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);
        }

    }
}

解决方案

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

这篇关于SqlDataReader的和并发/释放问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆