0

Here's what I understand about using HttpWebRequest to make a request asyncronously:

The essential structure for making an asynchronous web request is to call BeginGetResponse() and start a timer at the same time. If the response doesn't timeout, BeginGetResponse() will call a callback method that will call EndGetResponse() and read the response. If the response does timeout, a different callback method to the timer gets called and WebRequest.Abort() is invoked.

This structure hinges on the fact that Abort() and EndGetResponse() are exclusive. Calling Abort() after EndGetResponse() has basically no effect and calling EndGetResponse() after Abort() causes EndGetResponse() to throw an exception which can then be caught and handled however you want to handle timeouts.

My problem is when I need to make several hundred requests per second to several services and one service starts becoming very, very latent. The Timeout callback might get called after 500ms and calls Abort() and my program continues happily. But because the service still hasn't returned 10 seconds later, the first thread started by BeginGetResponse() is still waiting and the network connection resource is unavailable for use by any future requests.

Is there any way to have a timeout free up the resources of the thread that is supposedly timing out? If not, is there something like a Web.config value that I can set that will timeout the request on a different layer of the network than the application?

user779860
  • 665
  • 1
  • 7
  • 15
  • Here is the solution that we eventually came up with: – user779860 Jul 14 '12 at 19:08
  • We eventually came up with a solution that worked. We started our own threads, one for each HttpWebReqest, and then within those threads we called the synchronous GetResponse() rather than the asynchronous BeginGetResponse(). From what we can tell so far, the HttpWebRequest Timeout property that causes a WebException to be thrown seems to handle closing the connection and no longer waiting for a response from the server. I'm not sure about this, but it appears that HttpWebRequest should not be used asynchronously in cases where lots of connections to potentially really slow servers are needed. – user779860 Jul 14 '12 at 19:53

1 Answers1

0

free up the resources - This implies to me that your thread should have a destructor/finalizer which releases the unmanaged resources ( What exactly are unmanaged resources? ) that it has.

Community
  • 1
  • 1
Travis J
  • 81,153
  • 41
  • 202
  • 273
  • BeginGetResponse() starts its own thread that I don't control. If I did, I could implement a destructor to the thread that frees the network connection. The problem appears to be that there is no way to end the thread until the response comes from the server which could potentially be an infinite amount of time. I'm looking for a way around this. – user779860 Jul 07 '12 at 03:30