5

Should you always close a DataReader before closing the connection, or is it okay to just close the connection? By just closing the connection does that effectively close the reader?

(This is for c#.net 3.5)

Thanks!

skaffman
  • 398,947
  • 96
  • 818
  • 769
Dan H
  • 1,828
  • 2
  • 21
  • 38

3 Answers3

6

Aside from making your intent clear, there is this from the Microsoft documentation (Retrieving Data Using a DataReader (ADO.NET)):

You should always call the Close method when you have finished using the DataReader object.

Thomas
  • 63,911
  • 12
  • 95
  • 141
  • In my experience if you close the connection, but not the DataReader, you can get the error _The timeout period elapsed prior to obtaining a connection from the pool_. – Soma Holiday Feb 08 '14 at 22:47
0

Close the DataReader as well.

imo. if it implements IDisposable , or has a .close() method or a similar construct that the documentation states you should call when you're done with this instance - do it. Don't rely on something else to take care of it for you - unless the documentation explicitly states that it does. For a DataReader/DbConnection - the docs doesn't mention anything like this.

leeeroy
  • 11,216
  • 17
  • 52
  • 54
0

I prefer to leverage the c# using statment which will call dispose() for you. Here is a decent explanation.

Using Statment

Gratzy
  • 9,164
  • 4
  • 30
  • 45