Closing requisitions

2

I currently make multiple HTTP / HTTPS requests for distinct sites using the HttpWebRequest and HttpWebResponse classes using .NET Framework 4.0. We are experiencing a problem when a moment arrives we can not acquire SSL / TLS connection, as if arriving at a bottleneck. I would like to know if a request, made as below, causes error (entering a catch ) and proceeding to another so successively, whether this request is closed or not.

  PostData &= "&" & System.Web.HttpUtility.UrlEncode("btnOK", System.Text.Encoding.UTF8) & "=" & System.Web.HttpUtility.UrlEncode("OK", System.Text.Encoding.UTF8)

        url = "www.google.com.br"
        req = HttpWebRequest.Create(url)
        req.Method = "POST"
        req.Headers.Add(HttpRequestHeader.AcceptLanguage, "pt-BR")
        req.Headers.Add(HttpRequestHeader.Cookie, cookie)
        req.Headers.Add(HttpRequestHeader.Pragma, "no-cache")
        req.Referer = "www.google.com.br"
        req.UserAgent = "Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; rv:11.0) like Gecko"
        req.AutomaticDecompression = DecompressionMethods.GZip
        req.ContentType = "application/x-www-form-urlencoded"
        req.ContentLength = PostData.Length

    End If

End If

Try

    Dim swRequestWriter As StreamWriter = New StreamWriter(req.GetRequestStream())

    swRequestWriter.Write(PostData)
    swRequestWriter.Close()

    Dim srResponseReader As New StreamReader(req.GetResponse().GetResponseStream(), System.Text.Encoding.Default)

    Html = srResponseReader.ReadToEnd()

    swRequestWriter.Close()

    srResponseReader.Close()


Catch ex As Exception
    Throw ex
End Try
    
asked by anonymous 19.11.2015 / 13:06

1 answer

2

This way it is not closed no. If an error occurs, the close command is never executed, leaving the resource open, and sooner or later it will cause serious problems. The correct thing is to use the Using command to ensure that closing features that implement Disposable Pattern always happens ( see more ).

Never call Close() or Dispose() on your own. This causes resource leakage when there are errors.

In any case, you should probably fix the bugs. One of the reasons you are not fixing is that you are making another mistake. It is capturing the exception to do NOTHING. If there is nothing useful to do there, do not catch the exception, let it propagate to another place where something useful can be done. And if you still have nothing useful to do, let the application break. And fix the bug. Most of the exceptions are programming errors that should be fixed.

And before you say you're doing something when catching an exception, throw ex; is not something useful, it just destroyed the call stack. If it were the case, it should only do throw; , but it would still be a mistake to have only this line. This command is only useful coming after doing something useful. Alone he is a mistake. Take this exception "treatment" and read about it in tag

19.11.2015 / 13:26