Best Practice using HttpWebRequest & HttpWebResponse classes in Extensions


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 ( 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.


João Portela