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.
MK:
It works for XP, but not for Windows Server 2003 (64 bit), any help to fix it for Server 2003?
3/9/10, 16:13ripper234:
@MK, I don’t understand. What’s the problem with Server 2003?
3/9/10, 17:11MK:
I checked it with Windows XP, it worked when I deployed it to VPS(Windows server 2003), it did not worked and application stuck there.
Not sure what is issue, can u please guide me what could be reason.
3/9/10, 20:22