Posts Tagged ‘HttpWebRequest’

HttpWebRequest on Compact Framework: The operation has timed-out

With .Net Compact Framework I developed an application that is doing a webrequest on interval bases. With the webrequest I sent data by providing some arguments inside the querystring. I am not interested in the response and therefore I did not assign the GetResponse() return value. I use the following code:

HttpWebRequest webRequest;
try
{
   webRequest = WebRequest.Create("http://someurl.com/with.aspx?querystring=value");
   webRequest.Method = "GET";
   webRequest.KeepAlive = false;
   webRequest.GetResponse();
}
catch (Exception e){
    //Something goes wrong. Implement handling of this exception
}
finally {
   webRequest = null; //To clear up the webrequest
}

This code works… for only 2 times. The third time it is executed I get a: The operation has timed-out exception. It looks like the GetResponse() method keeps a connection (or socket) open which make it not possible to make new connection at the third time the method is executed. I solved this problem by assigning the GetResponse() value to a WebRequest variable and execute the Close() method inside the finally part of the try catch:

HttpWebRequest webRequest;
WebResponse webResponse = null; //Need to assign this as null otherwise it does not compile
try
{
   webRequest = WebRequest.Create("http://someurl.com/with.aspx?querystring=value");
   webRequest.Method = "GET";
   webRequest.KeepAlive = false;
   webResponse = webRequest.GetResponse(); //Assign to webResponse
}
catch (Exception e){
    //Something goes wrong. Implement handling of this exception
}
finally {
   if(webResponse != null)
   {
      webResponse.Close(); //Close webresponse connection
   }
   webResponse = null; //To clear up the webresponse
   webRequest = null; //To clear up the webrequest
}