Difference between StreamReader.Read and StreamReader.ReadBlock
Asked Answered
V

1

35

The documentation simply says ReadBlock is

"a blocking version of Read"

but what does that mean?

Someone else has asked the question before but, huh?

http://www.pcreview.co.uk/forums/thread-1385785.php

The guy answering said

Basically, it means that you can rely on StreamReader.ReadBlock not returning until either it's read as much as you've asked it to, or it's reached the end of the stream.

Am I understanding correctly that this is required because Read may not give you everything you asked for? And that just because it returns 0 does NOT mean you reached the end of the file?

So this means check something other than the number of bytes returned (EndOfStream?) or use ReadBlock instead?

Ventriculus answered 26/2, 2009 at 20:16 Comment(1)
Also see c# - When to use StreamReader.ReadBlock()? - Stack Overflow.Dipsomania
P
37

ReadBlock does not mean it is thread safe. 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.

Palomino answered 26/2, 2009 at 20:41 Comment(5)
If ReadBlock merely defers to Read until Read returns 0, what happens if Read returns 0 but the end of stream was not reached? Or is that impossible? If Read only returns what is ready, I would have thought it is theoretically possible that 0 could be returned at any time? Or is that wrong?Ventriculus
@J M: returning 0 always indicates that the end of the stream was reached, so Read is actually also blocking until it receives somethingTimtima
Ah - that is the final piece then. Read blocks until it at least has something and ReadBlock blocks until it's got everything you asked for or it hit the end of the file. Either way, 0 means end of file. That's great and thanks.Ventriculus
Ah... the word 'block' in ReadBlock refers to the action of blocking, not to the next 'block' of bytes.Dworman
Not to be pedantic, but TextReader is used to read characters, not bytes. The number of bytes may or may not equal the number of characters, depending on encoding.Kelcey

© 2022 - 2024 — McMap. All rights reserved.