I have a class the communicates with a device over TCP.
I send commands, and then issue stream.Read(reply, 0, 1) on the TcpClient’s GetStream().
I read out every single byte, and then combine the read bytes in a string, and compare the string to a termination string which lets me know when to stop reading.
There are some flaws in the device software, so that the termination string is not always sent. I would like to handle this in a proper way and using a period of time to determine whether the read should be stopped.
If I set the stream.ReadTimeout to something other than -1, then the socket will be closed when this timeout is exceeded, which I don’t want it to.
If I use the stream.BeginRead(..) with a stream.ReadTimeout = -1 then I will be sucking dry the thread pool after a while.
What intelligent solution can be constructed to address this issue?
I managed to implement something usingstream.DataAvailable.It goes like this:
where
socket = _tcpClient.Client;Edit:
socket.Receivealso closes the socket on timeout,socket.Polldoes not.Changed to usingsocket.Receive(..)instead ofstream.Read(..).