HttpWebResponse - proper use of the connection

I am working on a download manager in C # and I use several HTTP requests and wondered how can I make sure that the connection is closed properly?

Is it enough to call Dispose in the response stream? Do I need to call Close as well? Not sure if something might go wrong, but at some point the website will become unresponsive.

Thank!

+5
source share
2 answers

Wrap HttpWebResponsein the used block:

using(HttpWebResponse response = request.GetResponse())
{
    // do stuff here
} // response object is automatically disposed of here. 
+9
source

, HttpWebResponse . GetResponse() (, 404), HttpWebResponse .

HttpWebResponse webResponse = null;
try {
    webResponse = (HttpWebResponse)webRequest.GetResponse();
} catch (WebException e) {
    webResponse = (HttpWebResponse)e.Response;
    if (webResponse == null) {
        // Handle this.
    }
}    
using (webResponse) {
    // Process the response.
}
0

All Articles