HttpWebResponse - disposing of a connection properly
Asked Answered
A

2

5

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!

Aback answered 25/4, 2011 at 17:21 Comment(0)
S
9

Wrap your HttpWebResponse in a using block:

using(HttpWebResponse response = request.GetResponse())
{
    // do stuff here
} // response object is automatically disposed of here. 
Siderolite answered 25/4, 2011 at 17:25 Comment(2)
I'm familiar with the using statement but I'm already calling Dispose() after I'm done, is that any difference?Aback
When you use using like this, you don't need to worry about calling Dispose yourself, the compiler takes care of it for you.Siderolite
W
0

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.
}
Wirephoto answered 7/7, 2015 at 14:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.