Best Practice using HttpWebRequest & HttpWebResponse classes in Extensions

Best Practice using HttpWebRequest & HttpWebResponse classes in Extensions

  
Hi,

This week I notice that some of the extensions published in the Community could be incorrectly using classes HttpWebRequest/HttpWebResponse.

There are some known “connection leaks” in the .Net framework, so please remember to close all HttpWebRequest/HttpWebResponse’s after using them to avoid there “connection leaks”.

Here some usage advices/best practices of how to do it:

HttpWebResponse webresponse;
webresponse = (HttpWebResponse)webrequest.GetResponse();
…. webresponse.Close(); or
HttpWebResponse webresponse; using (webresponse = (HttpWebResponse)webrequest.GetResponse()) {
….
}

Explicitly closing the response will force the release of resources and release connection to the pool to be reused (http://msdn2.microsoft.com/en-us/library/system.net.httpwebresponse.close.aspx). This action will also “help” garbage collector to free up unused resources.

If you're developing extensions where you use these classes, please recheck your code.


Regards,

João Portela