In Albahari’s book C # 6.0 in a Nutshell, the following is written:
In fact, the
StreamReaderclassStreamReaderabsolutely forbidden to use withNetworkStream, even if you plan to call only theReadLinemethod. The reason is that the StreamReader class has a read ahead buffer, which can lead to reading more bytes than is currently available, and endless blocking (or until a socket timeout occurs). Other streams, such asFileStream, do not suffer from such incompatibility with theStreamReaderclass, because they support a certain terminating attribute, when reached, theReadmethod ends immediately, returning the value0.
What error, for example, in this class?
public class AsyncSocket : IDisposable { Socket socket; StreamReader sr; public AsyncSocket() { socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); sr = new StreamReader(new NetworkStream(socket)); } // ... остальные члены убраны public async Task<string> ReadLineAsync() { return await sr.ReadLineAsync(); } public void Dispose() { if (sr != null) sr.Close(); if (socket != null) socket.Dispose(); } } Let's say the string "123 \ r \ nqwe" came. StreamReader counts all of it into its internal buffer when calling ReadLineAsync() will return "123". Data from the internal buffer is not deleted the same? The second call to ReadLineAsync() will end when the end of the line arrives and the result is "qwe". Albahari writes about infinite blocking, so the normal Read method can lead to it if no data is sent to the socket.
Explain why you cannot use the StreamReader class with NetworkStream ?