c#
  • asp.net
  • .net
  • sql-server-2005
  • sqldatareader
  • 2012-05-23 51 views 0 likes 
    0

    運行下面的代碼是給我的錯誤:SqlDataReader對象和併發/釋放問題

    .NET框架執行升級策略由於內存不足的中止。 System.InvalidOperationException:已經有一個與此命令關聯的打開DataReader,它必須先關閉。

    我有以下代碼遍運行我的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(); 
        } 
    

    的GetDataReader由這個定義:

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

    在什麼行是拋出的異常? –

    +0

    你能給我們更多關於異常的細節嗎?它扔在哪裏?堆棧跟蹤等? [SqlDataReader對象的取消分配]的 –

    +0

    可能重複(http://stackoverflow.com/questions/10712860/deallocation-of-sqldatareader) –

    回答

    1

    鎖必須在讀者的水平.. 。多線程開放讀者

    +1

    我的思想完全吻合。確保您鎖定在讀者級別。 – Totero

    +0

    @Totero我很高興有人有禮貌評論。謝謝。可憐的東西從操作。垃圾郵件商人。 –

    +0

    垃圾郵件...百勝... :) – Totero

    相關問題