3

I have a confusion on how the ReadTimeout is used and how this affects Read().

When trying to read the network stream, there are 3 scenarios, assuming we are trying to read X number of bytes:

  1. Data is available, and bytes < X
  2. Data is available, and bytes = X
  3. Data is available, and bytes > X
  4. No data is available, and ReadTimeout > 0
  5. No data is available, and ReadTimeout = 0

The documentation is a bit ambiguous and does not explicitly mention about ReadTimeout in the call to Read(), or whether ReadTimeout affects Read() call at all.

This method reads data into the buffer parameter and returns the number of bytes successfully read. If no data is available for reading, the Read method returns 0. The Read operation reads as much data as is available, up to the number of bytes specified by the size parameter.

What I understand is for the above 5 scenarios:

  1. Read() will read in X bytes and return immediately. ReadTimeout does not matter
  2. Read() will read X bytes and return
  3. Read() will read X bytes and return. Need to call read again to read the rest of the X bytes.
  4. Call to Read() will wait for ReadTimeout period of time for data.
  5. Read() will return immediately with 0.

Would greatly appreciate if anybody can give some clarification.

Thank you.

DiskJunky
  • 4,750
  • 3
  • 37
  • 66
madu
  • 5,232
  • 14
  • 56
  • 96
  • 1
    `Read()` will block until data is available or the other side is closing the connection. I think the documentation is quite misleading here saying "if no data is available for reading, the Read method returns 0". – C.Evenhuis Oct 13 '17 at 09:05
  • 2
    You have to read documentation of [`ReadTimeout`](https://msdn.microsoft.com/en-us/library/bk6w7hs8(v=vs.110).aspx): *"amount of time that a read operation blocks waiting for data"*. `Read()` will actually block the caller until enough data are received to copy into buffer. Unless there is an error (you get `0` bytes) or timeout (you get less than you asked). – Sinatr Oct 13 '17 at 09:05
  • 2
    Actually `Read` will throw on timeout, so I don't know when it will return less. Blocking part is [correct](https://stackoverflow.com/a/6958290/1997232). – Sinatr Oct 13 '17 at 09:16
  • Thanks all. It is clear now. – madu Oct 14 '17 at 13:22

1 Answers1

1

If you look at the source for NetworkStream, you´ll see that your scenarios 1 - 4 and the understanding is correct (the NetworkStream just calls read() on the socket). The reult of an expired timeout is an IOException with an inner SocketException indicating timeout.

Scenario 5 does not apply: a ReadTimeout of zero cannot exist, it´s either minus 1 (-1, meaning infinite) or >= 1. So scen. 5 will be either block forever or get an IOException with an inner SocketException indicating some error.

C. Gonzalez
  • 689
  • 7
  • 8