Do I need to close System.Net.WebRequest ResponseStream?

I was wondering if I would end using any unclosed threads from this code:

Public Function [Get](ByVal url As String) As String Using reader = New System.IO.StreamReader(System.Net.WebRequest.Create(url).GetResponse.GetResponseStream) Return reader.ReadToEnd End Using End Function 

How about this:

  Public Function Get2(ByVal url As String) As String Using stream = System.Net.WebRequest.Create(url).GetResponse.GetResponseStream Using reader = New System.IO.StreamReader(stream) Return reader.ReadToEnd End Using End Using End Function 

Basically, you need to close System.Net.WebRequest ResponseStream ?

+4
source share
2 answers

You need to either close the response stream or close the response. Please note that closing StreamReader wrapping a Stream will still close the stream, so the first version should be fine. (Note that I consider “disposing of using the semantically equal operator” to close in the finally block “- there is no benefit in explicitly calling Close instead of just managing the stream or response.)

I believe that closing the stream is good enough - you also do not need to close the response - and, indeed, that is said in MSDN , but personally I do this for clarity:

 Public Function [Get](ByVal url As String) As String Using response = WebRequest.Create(url).GetResponse Using reader = New System.IO.StreamReader(response.GetResponseStream) Return reader.ReadToEnd End Using End Using End Function 

(There is a theoretical benefit that it closes the response if GetResponse returns successfully, but either the GetResponseStream constructor or the StreamReader constructor StreamReader an exception. I do not expect this to have practical consequences.)

If you don’t close anything, you can easily start timeouts in future requests to the same host - the answer “open” will essentially lead to a hang up of the connection to this host and by default there is a limit on two open connections to the host. This is a very common reason for timeouts - there are many SO questions where people get timeouts because they don't close anything.

+6
source

There is no need to call the Close method in WebResponse, but it is not harmful

http://msdn.microsoft.com/en-us/library/debx8sh9.aspx

+2
source

All Articles