How to close basic connections after catching httpwebrequest timeout

My asp.net application sends httpwebrequest to the remote REST server and waits for a response, and I found that there are many identical error messages like this:

System.Net.WebException: The operation has timed out. in System.Net.HttpWebRequest.GetResponse ()

Is it possible that after I catch this exception and close the basic http connection right away? or do I really not need to do this since I already set keepalive to false?

Thanks.

Actually one more question: if the timeout exception has always been in System.Net.HttpWebRequest.GetResponse(), does this mean that the application is waiting for a response from the remote server and cannot receive the response before the timeout expires. what could be the possible reason, the network connection is unstable? the remote server is not responding? any other possible reasons?

Here is the code:

 System.Net.HttpWebResponse httpWebResponse = null; System.IO.Stream stream = null; XmlTextReader xmlTextReader = null; try { System.Net.HttpWebRequest httpWebRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(request); httpWebRequest.ReadWriteTimeout = 10000; httpWebRequest.Timeout = 10000; httpWebRequest.KeepAlive = false; httpWebRequest.Method = "GET"; httpWebResponse = (System.Net.HttpWebResponse)httpWebRequest.GetResponse(); stream = httpWebResponse.GetResponseStream(); xmlTextReader = new XmlTextReader(stream); xmlTextReader.Read(); xmlDocument.Load(xmlTextReader); //Document processing code. //... } catch { //Catch blcok with error handle } finally { if (xmlTextReader != null) xmlTextReader.Close(); if (httpWebResponse != null) httpWebResponse.Close(); if (stream != null) stream.Close(); } 
+7
source share
4 answers

A simple rule of thumb is that if it does not implement IDisposal, it does not need to be disposed of.

+2
source

You can also increase the number of outgoing connections in the machine.config file:

 <system.net> <connectionManagement> <add address="*" maxconnection="2" /> </connectionManagement> </system.net> 

Change the maximum attr connection to something higher, see http://www.williablog.net/williablog/post/2008/12/02/Increase-ASPNET-Scalability-Instantly.aspx

+1
source

Make sure you position as well as close.

Or use blocks instead of try-finally:

 using (var httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse()) { using (var stream = httpWebResponse.GetResponseStream()) { using (var xmlTextReader = new XmlTextReader(stream)) { xmlDocument.Load(xmlTextReader); } } } 
0
source

Another thing you can do is call the Abort () method on the HTTPWebRequest, which results in an error, for example:

 catch (WebException we) { using (HttpWebResponse errorResp = we.Response as HttpWebResponse) { ... } request.Abort(); } 
0
source

All Articles