Some TextReader readers know that there will be more data soon, but not all characters are available right now. If you request 10 characters, and now only 4 characters are available, but the rest becomes available in a few seconds, then it might be wiser to return 4 available characters instead of waiting for all 10 characters.
An example is TextReader
which buffers data from a serial port: it will be too slow to wait until all requested characters become available, therefore, it will return all characters that are already available right now.
You can see the difference between TextReader.Read(char[], int, int)
and TextReader.ReadBlock(char[], int, int)
in the description of the return value:
TextReader.Read
Returns: the number of characters read, or 0 if no data was read at the end of the stream. The number will be less than or equal to the count parameter, depending on whether data is available in the stream.
TextReader.ReadBlock
Returns: the number of characters that have been read. The number will be less than or equal to the number, depending on whether all input characters have been read.
If you ask TextReader
Read
10 characters, Read
will be allowed to return no more than 10 characters if the reader believes that you should not wait for all 10 characters. As long as the reader knows that there are still characters, he will wait for at least one character. If Read
returns 4 bytes for reading, you do not know if the last character was read. Only if Read
returns zero, do you know there is nothing more to read. This allows TextReader to return the characters that are available right now, without having to wait for all 10 characters to become available.
ReadBlock
will wait until all 10 bytes are available (or EOF). Thus, a slow reader can block your process longer than you want.
To be sure that you have read all the characters, use 'Read repeatedly until you get a zero return; Use
repeatedly until you get a zero return; Use
ReadBlock' several times until you read fewer bytes than requested.