What is the difference between Read() and ReadBlock() calls on TextReader? [duplicate]
Asked Answered
P

1

7

The title more or less says it all. The calls are documented:

Here for TextReader.Read Method (Char[], Int32, Int32) and
Here for TextReader.ReadBlock() with the same argument types.

I want to extract a portion of a byte array, for which I make up a MemoryStream that I intent to read with a StreamReader like so:

    StreamReader r = new StreamReader(new MemoryStream(rawData, 0, 184, false, false));
    r.Read.....

Which one should I use? Is one of them faster or otherwise better?

Playlet answered 8/5, 2012 at 11:19 Comment(3)
ReadBlock attempts to return the requested number of bytes. if you get less then you know you hit the end of the stream.Toscanini
@HansPassant: Seems reasonable, as other commenters state, but where actually can I understand that from the documentation? IHMO, everybody is just guessing here.Playlet
I looked at the code, always a good way to find out what it is really doing. Reflector is handy, or just by browsing the Reference Source.Toscanini
G
9

If you can do something useful with a partial result, then call Read() and work on what you get. In particular if you are looping through and working on the result of each Read() then do this rather than with ReadBlock().

The word 'block' in ReadBlock refers to the action of blocking, not to the next 'block' of bytes. So it will force to stop further execution until it completed.

If you use Reflector to look at the implementation of StreamReader.ReadBlock (which is inherited from TextReader.ReadBlock), all it does is make multiple calls to the "Read" method until either the "Read" method returns 0 or we have read as many bytes as requested. This is needed because the "Read" method will not necessarily return as many bytes as you asked for.

Gobioid answered 9/5, 2012 at 5:54 Comment(2)
Thanks for clarifying about the term "block".Playlet
Cite your sources: https://mcmap.net/q/432443/-difference-between-streamreader-read-and-streamreader-readblockDalhousie

© 2022 - 2024 — McMap. All rights reserved.