为什么我得到"无效试图调用HasRows当阅读器被关闭"以开放的连接?

问题描述:

我有这个code:

// this is managed elsewhere
SqlConnection connection =...
connection.Open();

// this is one block of code, separate from the above
using( var transaction = connection.BeginTransaction() ) {
   using( var command = connection.CreateCommand() ) {
     command.Transaction = transaction;
     command.CommandText = ...
     using( var reader = command.ExecuteReader() ) {
         if( reader.HasRows ) {
             if( reader.Read() ) {
                 //get data from the reader
             }
         }
     }
}

这code运行得很好的大部分时间。然而,有时 - 很少 - 检索 HasRows 产生了以下异常:

Invalid attempt to call HasRows when reader is closed.
System.InvalidOperationException
  at System.Data.SqlClient.SqlDataReader.get_HasRows()
  // my code calling HasRows listed here

我是99.5%,确保连接在那一刻开启。我的code使用 HasRows 从阅读器的 pretty的MSDN很像表明

这可能是该异常的原因是什么?

What might be the reason for that exception?

这恰好是意外的行为在的ExecuteReader() - 很可能是一个错误。内心深处的ExecuteReader()一些随机的错误发生时,最有可能是网络超时,关闭连接,然后封闭 SqlDataReader的返回,​​就好像什么都没有发生。难怪后续调用 HasRows 产生一个例外。

This happens to be unexpected behavior in ExecuteReader() - most likely a bug. Deep inside ExecuteReader() some random error occurs, most likely a network timeout, the connection is closed and then a closed SqlDataReader is returned as if nothing happened. No wonder subsequent call to HasRows yields an exception.