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:

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

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:

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

Read more from the Uncategorized category. If you would like to leave a comment, click here: 5 Comments. or stay up to date with this post via RSS, or you can Trackback from your site.