Search code examples
c#.netidatareader

Execution Timeout Expired when closing IDataReader


I'm retrieving huge amount of data from SQL Server. Everything works fine but when I try to close IDataReader inside using statement

try
    {
      using (SqlConnection con = new SqlConnection(connString))
       {
         con.Open();
         using (SqlCommand command = new SqlCommand(sql_query, con))
         {
           command.CommandTimeout = 0;

           using (IDataReader rdr = new SqlCommand(sql_query, con).ExecuteReader(CommandBehavior.SequentialAccess))
            {
              dataTable = GetDataTableFromDataReader(rdr);
            }
             ....

I'm getting: Execution Timeout Expired. The timeout period elapsed prior to completion of the operation or the server is not responding.

Would it be better to use something like rdr = null? Or is there another better solution how to close IDataReader?


Solution

  • Note that there are timeout settings on both the connection and the command. You don't need to close or dispose manually inside a using block.

    You are creating a second SqlCommand in the using block which does not have a timeout set. Change to:

    using (IDataReader rdr = command.ExecuteReader(CommandBehavior.SequentialAccess))
    {
        dataTable = GetDataTableFromDataReader(rdr);
    }