This blog has moved to Medium

Subscribe via email


1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading ... Loading ...

Posts tagged ‘TimeoutStream’

TimeoutStream

What do you do when you want to read all the data from a Stream object in .NET? You use StreamReader.ReadToEnd().

Stream stream = ...;
StreamReader reader = new StreamReader(stream);
string data = reader.ReadToEnd();

Apparently there is no sane way to put a timeout on the above logic. If you call it and your stream doesn’t have a timeout, you’re doomed. Even if you stream has an internal timeout, you could still be doomed – for example, say you are reading from a website that sends you the letter ‘A’ every second. The timeout on the HttpResponseStream could be used, but still (assuming it’s higher than one second), you can’t set a timeout to the entire ReadToEnd() operation.

I wrote a small proxy class TimeoutStream that wraps any stream with a total timeout since the moment of its creation. Any blocking operation performed on it will fail if the stream has been created too far in the past.

I could use Asynchronous IO to sort of guarantee completion in this timeout without relying on a timeout on the stream itself – however, it appears to be impossible to do correctly in .NET – there is no good way to kill that IO operation if it does not complete within the allotted timeout (see here)- so far now this is good enough for our needs because we can indeed set a timeout on the HttpWebRequest object itself (in addition to using TimeoutStream).

The code is available here.