Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it necessary to manually close and dispose of SqlDataReader?

Tags:

c#

.net

sql

ado.net

I'm working with legacy code here and there are many instances of SqlDataReader that are never closed or disposed. The connection is closed but, I am not sure if it is necessary to manage the reader manually.

Could this cause a slowdown in performance?

like image 643
Jon Ownbey Avatar asked Apr 13 '09 14:04

Jon Ownbey


People also ask

Do I need to close SqlDataReader?

You must ensure the Close method is called when you are through using the SqlDataReader before using the associated SqlConnection for any other purpose. The Close method may either be called directly or through the Dispose method, disposing directly or in the context of the using statement block.

Do you need to close SqlConnection?

An application can call Close more than one time. No exception is generated. If the SqlConnection goes out of scope, it won't be closed. Therefore, you must explicitly close the connection by calling Close or Dispose .

How do I close an ExecuteReader?

If you use . ExecuteReader(CommandBehavior. CloseConnection); then by disposing the READER, the connection will be closed.

Which of these are ways to close the SqlDataReader after the rows returned by the SQL command are processed?

When the return values and the number of records affected by a query are not significant, the time that it takes to close the SqlDataReader can be reduced by calling the Cancel method of the associated SqlCommand object before calling the Close method.


1 Answers

Try to avoid using readers like this:

SqlConnection connection = new SqlConnection("connection string"); SqlCommand cmd = new SqlCommand("SELECT * FROM SomeTable", connection); SqlDataReader reader = cmd.ExecuteReader(); connection.Open(); if (reader != null) {       while (reader.Read())       {               //do something       } } reader.Close(); // <- too easy to forget reader.Dispose(); // <- too easy to forget connection.Close(); // <- too easy to forget 

Instead, wrap them in using statements:

using(SqlConnection connection = new SqlConnection("connection string")) {      connection.Open();      using(SqlCommand cmd = new SqlCommand("SELECT * FROM SomeTable", connection))     {         using (SqlDataReader reader = cmd.ExecuteReader())         {             if (reader != null)             {                 while (reader.Read())                 {                     //do something                 }             }         } // reader closed and disposed up here      } // command disposed here  } //connection closed and disposed here 

The using statement will ensure correct disposal of the object and freeing of resources.

If you forget then you are leaving the cleaning up to the garbage collector, which could take a while.

like image 116
Codebrain Avatar answered Sep 20 '22 16:09

Codebrain