Question

Following is a statement from SqlDataReader Class

While the SqlDataReader is being used, the associated SqlConnection is busy serving the SqlDataReader, and no other operations can be performed on the SqlConnection other than closing it.

I have code that has one open connection used by two different commands. There are actually two methods. The second method is getting called in the while(reader.Read()) loop.

I get intermittent errors saying – There is already an open DataReader associated with this Command which must be closed first.

But why isn’t it always throwing error?

REFERENCES

  1. Default Result Set Processing and Multiple Active Result Sets
  2. SQL Server Connection Basics
  3. Regarding a small confusion about DataReader

enter image description here

Was it helpful?

Solution

now that you know that nested datareaders over the same connection is a bad idea, why are you even doing that? do refactor that code.

now to answer your question,

Network layer does not work in PULL mode. You open a connection, issue some command and then start consuming the results. Note you do NOT pull but consume. there is a difference. in your code, while(reader.Read) loop does not steadily pull data. the data starts arriving the moment the command is executed. it gets buffered at your pc. The buffer has a limit. if total data is less than the buffer size then the data-transfer happens really fast. if total data is more than the buffer size then of course the reader.read() makes room for next batch.

This means that two DataReaders can work with same connection as long as the first datareader fetches very little amount of data. so by the time the second datareader attempts to use the connection the connection has already gone idle.

there is a race condition between two threads. first thread is the one which collects the data sent in response to the first command. the second thread is the one on which your program is running. both race to complete first. if the collector thread is able to download all data before your main thread hits second datareader then the accident is averted. but if the data is large or network is slow, or by sheer luck it didnt get enough cpu, then the main thread hits second datareader while the connection is still working.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top