Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 916
Meniya Avatar asked Apr 25 '11 17:04

Meniya


People also ask

What is dispose method in httpwebresponse?

HttpWebResponse.Dispose(Boolean) HttpWebResponse.Dispose(Boolean) HttpWebResponse.Dispose(Boolean) HttpWebResponse.Dispose(Boolean) Method. Definition. Releases the unmanaged resources used by the HttpWebResponse, and optionally disposes of the managed resources.

What does the disposing parameter do in a webresponse?

When the disposing parameter is true, this method releases all resources held by any managed objects that this WebResponse references. This method invokes the Dispose () method of each referenced object. This member outputs trace information when you enable network tracing in your application.

Why httpcontext should never dispose its result?

From the outside a user just see HttpContext implements IDisposable and so he have to dispose. Thats it. Or in other words: HttpContext never should Dispose its result aka the Stream, because also Stream implements IDisposable and the user therefore knows that he have responsibility for it and that he have to dispose.

Do I need to dispose of the response content or stream?

The model is that you need to dispose of the response content or stream; you can but do not need to dispose of both. The handler that creates the response content and stream is responsible for ensuring resources are appropriately cleaned up according to that contract. Sorry, something went wrong.


1 Answers

Wrap your HttpWebResponse in a using block:

using(HttpWebResponse response = request.GetResponse())
{
    // do stuff here
} // response object is automatically disposed of here. 
like image 55
Kyle Trauberman Avatar answered Oct 07 '22 19:10

Kyle Trauberman