Meniya
Meniya

Reputation: 197

HttpWebResponse - disposing of a connection properly

I'm working on a download manager in C# and I'm making using of multiple http requests and was wondering how can one make sure a connection properly closed?

Is it enough to call Dispose on the response stream? Do I need to call Close as well? Not sure where things could possibly could go wrong but at some point a web site would become unresponsive.

Thanks!

Upvotes: 5

Views: 1832

Answers (2)

Stefan
Stefan

Reputation: 1268

As Kyle mentioned, wrap your HttpWebResponse in a using block. But if GetResponse() throws an exception (which happens on a 404 response, for instance), you need to grab the HttpWebResponse in the exception.

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

Upvotes: 0

Kyle Trauberman
Kyle Trauberman

Reputation: 25694

Wrap your HttpWebResponse in a using block:

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

Upvotes: 9

Related Questions