Saturday, February 11, 2012

HttpWebRequest fails after few requests and throws timeout exception.

 Problem
       HttpWebRequest fails after few (2) request and throws timeout exception

Scenario
 Sequential request: You are making sequential request for same of different urls
  webReq = (HttpWebRequest)WebRequest.Create(url);
  webResp = (HttpWebResponse)webReq.GetResponse();

  webReq = (HttpWebRequest)WebRequest.Create(url);
  webResp = (HttpWebResponse)webReq.GetResponse();
  webReq = (HttpWebRequest)WebRequest.Create(url);
  webResp = (HttpWebResponse)webReq.GetResponse();


Service Point Manager that handles the http request created by HttpWebRequest     object do not allow to create more than 2 conection and request is once opened   it is not get closed automaticly and HttpWebRequest object never get garbage collected because it is always accesable via Service Point Manager object.

Solution : Always explicitly closed HttpWebResponce object  webResp.Close()

 Parallel request : You are making multiple request in parallel using threads.
  By default Service Point Manager has a connection limit of 2 so it will not allow placing more than two request.
  Solution: change connection limit by setting service point manager property ServicePointManager.DefaultConnectionLimit

Further References
http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.aspx

No comments:

Post a Comment