开发者

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 wron开发者_Go百科g but at some point a web site would become unresponsive.

Thanks!


Wrap your HttpWebResponse in a using block:

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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜