views:

682

answers:

2

I've set both Timeout and ReadWriteTimeout of HttpWebRequest, and still GetRequestStream does not time out when trying to connect to a non-existent server. I've run into similar problems in the past when the DNS resolution was struck, but this time the server in question is running on my own machine (localhost) so this not relevant.

The scenario is this:

  1. I raise my server
  2. I successfully connect to it, perform a POST, and close the request / response stream
  3. I kill the server
  4. I try to connect again, and expect that I will hit the timeout I set

At this point the thread hangs. I tried setting KeepAlive to false, but that didn't help.

I thought about running the above scenario in a separate thread, and if it takes too long kill it myself - however this solution is very ugly and won't prevent resource leaks.

+1  A: 

Try using BeginGetRequestStream and EndGetRequestStream instead of GetRequestStream. Set up a timer and call EndGetRequestStream prematurely after enough time has elapsed that you assume the request will hang. Obviously you must also call EndGetRequestStream in the delegate passed in to BeginGetRequestStream if you do process the request normally so there has to be some synchronization between the two threads to keep from calling EndGetRequestStream twice.

Glenn
Of course, not sure how I missed this one :)
ripper234
A: 

Are you sure that the thread is hanging? If I remember correctly, the default timeout on the HttpWebRequest is 2 minutes. GetRequestStream() will cause the request to be sent first and it should timeout after two minutes.

Also note that this timeout is dependent on other things (for eg DNS). So, if sending a request entails doing a DNS request, and if the DNS request takes a long time to respons, then the timeout might be longer than 2 minutes.

Normally, you shouldnt need to do what Glenn is suggesting. If the timeout is not working with GetRequestStream(), it might be a bug.

Can you get a trace log with http://ferozedaud.blogspot.com/2009/08/tracing-with-systemnet.html and post the trace here and we can see what is going on?

feroze