Do we need to close the System.Net.WebRequest's ResponseStream?

Pacerier picture Pacerier · Sep 12, 2011 · Viewed 9.9k times · Source

I was wondering will I end up having any unclosed streams 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

What 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, do we need to close the System.Net.WebRequest's ResponseStream ?

Answer

Jon Skeet picture Jon Skeet · Sep 12, 2011

You either need to close the response stream or you need to close the response. Note that closing a StreamReader wrapping a Stream will close the stream anyway, so the first version should be okay. (Note that I'm deeming "dispose with a Using statement" to be semantically equal to "close in a finally block" - there's no benefit in explicitly calling Close instead of just disposing of the stream or response.)

I believe that closing the stream is good enough - that you don't need to close the response as well - and indeed that's what MSDN states, but personally I'd do so 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's a theoretical benefit here that it will close the response if GetResponse returns successfully but either GetResponseStream or the StreamReader constructor throws an exception. I don't expect that to have any practical implications.)

If you don't close anything, you could very easily run into timeouts in future requests to the same host - the "open" response will essentially hog the connection to that host, and by default there's a limit of two open connections per host. This is a very common cause of timeouts - there are lots of SO questions where folks are getting timeouts due to not closing anything.