Some TextReaders know that there will be more data soon, but that not all characters are available right now. If you ask for 10 characters, and there are now only 4 characters available, but the other ones will become available in a few seconds, then it might be wiser to return the 4 available characters instead of waiting for all 10 characters.
An example could be a TextReader
that bufferst data from a serial port: it would be too slow to wait until all requested characters are available, hence 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)
at the description of the return value:
TextReader.Read
Returns:
The number of characters that have been read, or 0 if at the end of the stream
and no data was read. The number will be less than or equal to the count parameter,
depending on whether the data is available within the stream.
TextReader.ReadBlock
Returns:
The number of characters that have been read. The number will be less than or
equal to count, depending on whether all input characters have been read.
If you ask a TextReader
to Read
10 characters, Read
is allowed to return with less than 10 characters if the reader thinks that it is not wise to wait for all 10 characters. As long as the reader knows that there are still characters, it will wait for at least one character. If Read
returns that 4 bytes are read, then you don't know if the last character has been read. Only if Read
returns zero you know there is nothing to read anymore. This allows the TextReader to return the characters that are available right now without having to wait for all 10 characters to become available.
ReadBlock
would wait until all 10 bytes become available (or EOF). So a slow reader might block your process longer than you desire.
To be certain that you've read all characters, Use 'Readrepeatedly until you get a zero return; Use
ReadBlock` repeatedly until you read less bytes than requested.