madu
madu

Reputation: 5450

NetworkStream: ReadTimeout and its effect Read()

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.

Upvotes: 3

Views: 6941

Answers (1)

C. Gonzalez
C. Gonzalez

Reputation: 724

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.

Upvotes: 1

Related Questions