tags:

views:

49

answers:

1

Hi,

I would like to know of a situation Read(char[],int,int) fails to return all chars requested while ReadBlock() returns all chars as expected (say when StreamReader works with an instance of a FileStream object).

Thanks.

A: 

It's a major issue on network streams particularly if the Streamed data is quite large and the server providing the Stream does so as chunked output (i.e. quite typical with HTTP) since a call to just Read() i.e. the single character read gives -1 once the EOS is reached, calls to Read(char[], int, int) with arguments gets up to the number of characters asked for or less if the EOS is reached and then returns the number of characters read or zero if the EOS has been reached

Whereas ReadBlock() waits for data to be available from the Stream so you never run into this issue.

One other thing to note is that both forms reads a maximum number of characters and are not guaranteed to return that many characters if there aren't that many available

I asked a question on a similar topics some time ago - http://stackoverflow.com/questions/1264952/reading-from-a-httpresponsestream-fails - when I had issues reading from HTTP streams

RobV
'since Read() would return a -1 for the end of stream once it reaches the end of the buffered data even if all the data from the stream had not been received'. No it wouldn't. It would return the final number of bytes received and then the EOS indication. You would never lose data.
EJP
@RobV – Thanks for your input! But I’m not sure if ReadBlock() waits anymore if Read() returns EOS indication. I thought ReadBlock()’s waiting logic is implemented through repeated calls to Read() till it collects all the chars requested or hits EOS. Or is it not?
RanC
@EJP sorry I kinda paraphrased a bit there - I know you would not lose data
RobV
@RanC not sure how it's implemented internally but I use the ReadBlock() approach for handling network streams and don't have any issues
RobV
@EJP Clarified my answer to cover both forms of `Read()`
RobV